<?php

namespace App\Services;

use App\Models\Provider;
use App\Models\Schedule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ProviderCalendarService
{
    public function __construct() {}

    public function getCalendar(): array
    {
        $user = Auth::user();

        $provider = Provider::where('user_id', $user->id)->first();

        $selectFields = [
            'schedules.id',
            'schedules.client_id',
            'client_user.name as client_name',
            'schedules.date',
            'schedules.start_time',
            'schedules.end_time',
            'schedules.total_amount',
            'schedules.period_type',
            'schedules.schedule_type',
            'schedules.address_id',
            'schedules.status',
            'custom_schedules.offers_meal',

            DB::raw("
                (
                    SELECT media.path
                    FROM media
                    WHERE media.source_id = clients.id
                    AND media.source = 'client'
                    AND media.deleted_at IS NULL
                    LIMIT 1
                ) AS customer_photo
            "),

            DB::raw("
                EXISTS (
                    SELECT 1
                    FROM reviews
                    WHERE reviews.schedule_id = schedules.id
                    AND reviews.origin = 'provider'
                    AND reviews.origin_id = {$provider->id}
                    AND reviews.deleted_at IS NULL
                ) AS provider_reviewed
            "),

            DB::raw("
                (
                    SELECT reviews.stars
                    FROM reviews
                    WHERE reviews.schedule_id = schedules.id
                    AND reviews.origin = 'provider'
                    AND reviews.origin_id = {$provider->id}
                    AND reviews.deleted_at IS NULL
                    LIMIT 1
                ) AS provider_stars
            "),

            DB::raw("
                (
                    SELECT service_package_items.service_package_id
                    FROM service_package_items
                    WHERE service_package_items.schedule_id = schedules.id
                    LIMIT 1
                ) AS service_package_id
            "),
        ];

        $signPhoto = fn ($item) => tap($item, fn ($i) => $i->customer_photo = $i->customer_photo
            ? Storage::temporaryUrl($i->customer_photo, now()->addMinutes(60))
            : null);

        $upcomingSchedules = Schedule::with('address:district,address,number,source_id,source,id')
            ->where('schedules.provider_id', $provider->id)
            ->whereIn('schedules.status', ['pending', 'accepted', 'paid', 'started'])
            ->whereDate('schedules.date', '>=', now()->toDateString())
            ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
            ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
            ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
            ->select($selectFields)
            ->orderBy('schedules.date', 'asc')
            ->orderBy('schedules.start_time', 'asc')
            ->get()
            ->map($signPhoto);

        $completedSchedules = Schedule::with('address:district,address,number,source_id,source,id')
            ->where('schedules.provider_id', $provider->id)
            ->whereIn('schedules.status', ['finished', 'cancelled'])
            ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
            ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
            ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
            ->select($selectFields)
            ->orderBy('schedules.date', 'desc')
            ->orderBy('schedules.start_time', 'desc')
            ->get()
            ->map($signPhoto);

        return [
            'upcomingSchedules'  => $upcomingSchedules,
            'completedSchedules' => $completedSchedules,
        ];
    }
}
