<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Site\SiteController;
use Illuminate\Http\Request;
use App\Models\Booking\SchServiceBooking;
use App\Models\Customer\CmnCustomer;
use App\Models\Settings\CmnBranch;
use App\Models\Services\SchServices;
use App\Models\Employee\SchEmployee;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;
use App\Enums\ServiceStatus;
use Carbon\Carbon;
use ErrorException;

class BookingController extends Controller
{
    public function cancelAppointment(Request $request){
        $siteController = new SiteController();
        return $siteController->cancelService($request->booking_no);
    }

    public function searchAppointments(Request $request){
        //dd($request->email);
        \Log::info($request->phone); 
        $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')
        ->join('sch_employees', 'sch_service_bookings.sch_employee_id', '=', 'sch_employees.id')
        ->where('cmn_customers.phone_no', '+'.$request->phone)
        ->whereDate('sch_service_bookings.date', '>=', Carbon::now()->addHours(8)->toDateString()) // Adjust to compensate +8 GMT issue
        ->where('sch_service_bookings.status', '<', 3)
        ->select([
            'sch_service_bookings.id',
            'cmn_branches.name as branch',
            'cmn_branches.short_name as short_branch',
            'sch_service_bookings.cmn_branch_id',
            'sch_employees.full_name as employee',
            'sch_service_bookings.sch_employee_id',
            'cmn_customers.full_name as customer',
            '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'
        ]);


        if (($request->user_type ?? 'existing') == 'new') {
            $appointments = $appointments->orderBy('sch_service_bookings.updated_at', 'desc')->first();
        }else if(($request->user_type ?? 'existing') == 'confirmed'){
            $appointments = $appointments->where('sch_service_bookings.status', '=', '2')->first();
        }
        else{
            $appointments = $appointments->orderBy('sch_service_bookings.id', 'desc')->get();
        }

        if ($request->send_msg) {
            if ($appointments->count() > 0) {
                return $this->apiResponse(['status' => '1'], 200);
            }else{
                return $this->apiResponse(['status' => '0'], 200);
            }
        }        

        $upcomingAppointments = array();

        if (is_numeric($request->user_input)) {
            if ($appointments->count() > 0) {
                //dd($request->user_input, $appointments);
                $validateRecord = $appointments->where('id', $request->user_input);
                if ($validateRecord->count() > 0) {
                    return $this->apiResponse(['status' => '1'], 200);
                }else{
                    return $this->apiResponse(['status' => '0'], 200);
                }
            }
        }else{
            if ($request->user_type) {
                return $this->apiResponse(['status' => '1', 'new_booking_number' => $appointments->id, 'short_name'=> $appointments->short_branch], 200);
            }
        }
        
        foreach ($appointments as $appointment) {
            $serviceDate = new Carbon($appointment->date);
            $appointmentStatus = ServiceStatus::wordFromValue($appointment->status);
            $appointment->start_time = Carbon::createFromFormat('H:i:s', $appointment->start_time)->format('H:i');
            $appointment->end_time = Carbon::createFromFormat('H:i:s', $appointment->end_time)->format('H:i');

            // Initialize variables
            $bookingNo = "*Booking No: $appointment->id*\n";
            $bookedUnder = "Booked Under: $appointment->customer\n";
            $service = "Service: $appointment->service\n";
            $date = "Date: {$serviceDate->format('D, M d, Y')}\n";
            $time = "Time: $appointment->start_time - $appointment->end_time\n";
            $location = "Location: $appointment->branch\n";
            $status = "Status: $appointmentStatus\n";

            // Conditionally add the Booked For line
            $bookedFor = "";
            if (!empty($appointment->SomeBody_Name)) {
                $bookedFor = "Booking For: $appointment->SomeBody_Name\n";
            }

            // Construct the final message
            $whatsapp_message = $bookingNo . $bookedUnder . $bookedFor . $service . $date . $time . $location . $status;
            //$whatsapp_message = "*Booking No: $appointment->id*\nName: $appointment->customer\nService: $appointment->service\nDate: {$serviceDate->format('D, M d, Y')}\nTime: $appointment->start_time - $appointment->end_time\nLocation: $appointment->branch\nStatus: $appointmentStatus";
            //$telegram_message = "Dear $user->name,\n\nThis is a confirmation notice of your appointment\n\nBooking No: $updateData->id\nName: $user->name\nService: $serviceName\nDate: {$serviceDate->format('D, M d, Y')}\nTime: $updateData->start_time - $updateData->end_time\nLocation: $branchName";
            //$identifier = 'phone:+'.$customer->phone_no;

            $identifier = 'phone:'.$request->phone;

            // Commented out on 11/6/2025

            // Send message via Respond.io API
            // $response = Http::withHeaders([
            //     'Accept' => 'application/json',
            //     'Authorization' => 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NjYyMiwic3BhY2VJZCI6MTU2NTE0LCJvcmdJZCI6MTU4MDM2LCJ0eXBlIjoiYXBpIiwiaWF0IjoxNzExOTYwMjg4fQ.wLWuSYTPI-NhULIg5jtuzKFuCmhG91MvI77goMYOn_I',
            //     'Content-Type' => 'application/json',
            // ])->post('https://api.respond.io/v2/contact/'.$identifier.'/message', [
            //     'message' => [
            //         // 'text' => $whatsapp_message,
            //         'text' => $whatsapp_message,
            //         'type' => 'text'
            //     ], 
            //     'channelId' => 0,
            // ]);
    
            // if ($response->successful()) {
            //     // Message sent successfully
            //     $upcomingAppointments[] = ['booking_no' => $appointment->id, 'response_msg' => $response->json()];    
            // } else {
            //     // Failed to send message
            //     return false;
            // }

            // $response = Http::withHeaders([
            //     'Accept' => 'application/json',
            //     'Authorization' => 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NjYyMiwic3BhY2VJZCI6MTU2NTE0LCJvcmdJZCI6MTU4MDM2LCJ0eXBlIjoiYXBpIiwiaWF0IjoxNzExOTYwMjg4fQ.wLWuSYTPI-NhULIg5jtuzKFuCmhG91MvI77goMYOn_I',
            //     'Content-Type' => 'application/json',
            // ])->put('https://api.respond.io/v2/contact/'.$identifier, [
            //     'custom_fields' => [
            //        'name' =>
            //     ]
            // ]);
    
            // if ($response->successful()) {
            //     // Message sent successfully
            //     $upcomingAppointments[] = ['booking_no' => $appointment->id, 'response_msg' => $response->json()];    
            // } else {
            //     // Failed to send message
            //     return false;
            // }
        }
        // dd($upcomingAppointments);
        if (!empty($upcomingAppointments)) {
            return $this->apiResponse(['status' => '1', 'data' => $upcomingAppointments], 200);
        }else{
            return $this->apiResponse(['status' => '0', 'data' => $upcomingAppointments], 200);
        }

    }


    
        
}