<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\Booking\SchServiceBooking;
use App\Http\Repository\Booking\BookingRepository;


class AutoApproveBookings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:auto-approve-bookings';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Job to auto approve booking appointments that are 12 hours old from the time of booking';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    protected $bookingRepository;

    public function __construct(BookingRepository $bookingRepository)
    {
        parent::__construct();
        $this->bookingRepository = $bookingRepository;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $today = Carbon::today()->toDateString();

        $appointments = SchServiceBooking::join('cmn_customers', 'sch_service_bookings.cmn_customer_id', '=', 'cmn_customers.id')
            ->join('sch_services', 'sch_service_bookings.sch_service_id', '=', 'sch_services.id')
            ->join('cmn_branches', 'sch_service_bookings.cmn_branch_id', '=', 'cmn_branches.id')
            ->where('sch_service_bookings.status', '=', 0)
            ->where(function ($query) {
                $query->where('sch_service_bookings.created_at', '<=', Carbon::now()->subHours(12))
                    ->orWhereNull('sch_service_bookings.created_at');
            })
            ->whereDate('sch_service_bookings.date', '>', $today)
            ->select([
                'sch_service_bookings.id',
                'cmn_branches.name as branch',
                'sch_service_bookings.cmn_branch_id',
                'cmn_customers.full_name as customer_name',
                'cmn_customers.fullName_S as someoneelse',
                'sch_service_bookings.cmn_customer_id',
                'cmn_customers.phone_no',
                'cmn_customers.email',
                'sch_service_bookings.date',
                'sch_service_bookings.sch_service_id',
                'sch_services.title as service',
                'sch_services.sch_service_category_id',
                'sch_service_bookings.start_time',
                'sch_service_bookings.end_time',
                'sch_service_bookings.is_checked',
                'sch_service_bookings.SomeBody_Name',
                'sch_service_bookings.status',
                'sch_service_bookings.remarks'
            ])
            ->orderBy('sch_service_bookings.id', 'desc')
            ->get();
            
        foreach ($appointments as $appointment) {
            
            // Change status to 'Approved'
            $this->bookingRepository->ChangeBookingStatus($appointment->id, 2, 1);

        }
    }
}
