<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CarOwner;
use App\Models\CarOwnerCar;
use App\Models\PreBooking;
use App\Models\BodyType;
use App\Models\WashCategoryBodyType;
// use App\Models\WashTypeToPrebooking;
use App\Models\CarWashOwner;
use App\Models\WashTypeToWash;
use App\Models\OptionalExtra;
use App\Models\CleanerWash;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Config;
use Hash;
use Auth;

class CwoPreBookingController extends Controller
{
    public function __construct()
    {
    }

    public function index()
    {
    }

    public function list(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'cwo_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $cwo_id = $request->input('cwo_id');

        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.name', 'pre_bookings.isd_code', 'pre_bookings.phone_no', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.address', 'pre_bookings.body_type_id', 'pre_bookings.body_type', 'pre_bookings.amount', 'pre_bookings.total_amount', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'pre_bookings.co_id', 'currency_masters.symbol', 'pre_booking_types.type')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('pre_bookings.cwo_id', $cwo_id);
        $data = $data->orderBy('pre_bookings.id', 'desc');
        $dataCount = $data->count();
        $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit;   

        $dataDisplay=[];
        $dataArray = [];
        if($data != '') {
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['prebooking_type'] = $d->type;
                $dataDisplay['name'] = $d->name;
                $dataDisplay['isd_code'] = $d->isd_code;
                $dataDisplay['phone_no'] = $d->phone_no;
                if($d->date != '') {
                    $dataDisplay['date']  = date("d/m/Y", strtotime($d->date));
                } else {
                    $dataDisplay['date']  = '';
                }
                if($d->time != '') {
                    $dataDisplay['time']  = date("h:i a", strtotime($d->time));
                } else {
                    $dataDisplay['time']  = '';
                }
                $dataDisplay['date_time'] = $d->date_time;
                $dataDisplay['address'] = $d->address;
                $dataDisplay['body_type_id'] = $d->body_type_id;
                $dataDisplay['body_type'] = $d->body_type;
                $dataDisplay['amount'] = $d->amount;
                $dataDisplay['total_amount'] = $d->total_amount;
                $dataDisplay['status_id'] = $d->status;
                if($d->status == 1) {
                    $dataDisplay['status'] = 'Pending';
                }
                if($d->status == 2) {
                    $dataDisplay['status'] = 'Confirmed';
                }
                if($d->status == 3) {
                    $dataDisplay['status'] = 'Declined';
                }
                $dataDisplay['car_id'] = $d->car_id;
                $dataDisplay['car_registration_no'] = $d->car_registration_no;
                $dataDisplay['co_id'] = $d->co_id;
                if($d->symbol != '') {
                    $dataDisplay['currency'] = $d->symbol;
                } else {
                    $dataDisplay['currency'] = 'R';
                }

                $wash_types = WashTypeToWash::select('wash_categories.wash_name', 'wash_type_to_washes.price')
                            ->join('wash_categories', 'wash_categories.id', '=', 'wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.prebooking_id', $d->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
                $dataDisplay['wash_types'] = $wash_types;

                $optionalExtra = OptionalExtra::where('prebooking_id', $d->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
                $dataDisplay['extras'] = $optionalExtra;

                $dataArray[] = $dataDisplay;
            }
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'preBookingCount' => $dataCount,
            'preBookingList' => $dataArray
        ]);
    }

    public function preBookingAllStatus(Request $request){
        $preBookingAllStatus = [
            [
                'id' => 2,
                'name' => 'Confirm',
            ],
            [
                'id' => 3,
                'name' => 'Decline',
            ]

        ];

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'preBookingAllStatus' => $preBookingAllStatus
        ]);
    }

    public function preBookingChangeStatus(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_id' => 'required',
                'status' => 'required',
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');
        $status = $request->input('status');

        $record = PreBooking::find($prebooking_id);
        $record->status = $status;
        $record->save();

        $getCwo = CarWashOwner::where('id', $record->cwo_id)->select('cwo_company')->first();
        $cwo_company = $getCwo->cwo_company;
        $getCar = CarOwnerCar::where('id', $record->car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;
        $getCo = CarOwner::where('id', $record->co_id)->select('co_fname', 'co_lname', 'email', 'fcm_token')->first();
        if($record->name != '') {
            $recipient_name = $record->name;
        } else {
            $recipient_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $email = $getCo->email;
        $fcm_token = $getCo->fcm_token;

        if($status == 2) {
            $status_text = 'confirmed';
        }
        if($status == 3) {
            $status_text = 'declined';
        }

        /*send mail starts*/
        if($email != ''){
            $recipient_email = $email;
            // echo $recipient_email;exit;
            $subject = 'Autoclick Car Pre Booking ' . ucfirst($status_text);
            $message_body = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking ' . ucfirst($status_text) . '</title>
                                </head>
                                <body>
                                    <p>Hi ' . $recipient_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been ' . $status_text . ' at  ' . $cwo_company . '. Thank you!</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';
            // echo $message_body;exit;
            $email = sendMail(array($recipient_name, $recipient_email), $message_body, $subject);
            // print_r($email);exit;
        }
        /*send mail ends*/

        /*push starts*/
        // $notification_title = 'Autoclick Car Pre Booking ' . ucfirst($status_text);
        // $notification_body = 'Pre booking for your car ' . $car_registration_no . ' has been ' . $status_text . ' at ' . $cwo_company;
        // // echo $notification_title . ' ->' . $notification_body;exit;
        // $data=array("request_type" => "notification");
        // sendFcmNotification($fcm_token, $notification_title, $notification_body, $data);
        /*push ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Pre booking has been ' . $status_text . ' successfully'
        ]);
    }

    public function detail(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');

        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.name', 'pre_bookings.isd_code', 'pre_bookings.phone_no', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.address', 'pre_bookings.body_type_id', 'pre_bookings.body_type', 'pre_bookings.amount', 'pre_bookings.total_amount', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'pre_bookings.co_id', 'currency_masters.symbol', 'pre_booking_types.type')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('pre_bookings.id', $prebooking_id)
            ->first();
        // echo "<pre>";print_r($data->toArray());exit;   

        $dataDisplay=[];
        if($data != '') {
            $dataDisplay['id'] = $data->id;
            $dataDisplay['prebooking_type'] = $data->type;
            $dataDisplay['name'] = $data->name;
            $dataDisplay['isd_code'] = $data->isd_code;
            $dataDisplay['phone_no'] = $data->phone_no;
            if($data->date != '') {
                $dataDisplay['date']  = date("d/m/Y", strtotime($data->date));
            } else {
                $dataDisplay['date']  = '';
            }
            if($data->time != '') {
                $dataDisplay['time']  = date("h:i a", strtotime($data->time));
            } else {
                $dataDisplay['time']  = '';
            }
            $dataDisplay['date_time'] = $data->date_time;
            $dataDisplay['address'] = $data->address;
            $dataDisplay['body_type_id'] = $data->body_type_id;
            $dataDisplay['body_type'] = $data->body_type;
            $dataDisplay['amount'] = $data->amount;
            $dataDisplay['total_amount'] = $data->total_amount;
            $dataDisplay['status_id'] = $data->status;
            if($data->status == 1) {
                $dataDisplay['status'] = 'Pending';
            }
            if($data->status == 2) {
                $dataDisplay['status'] = 'Confirmed';
            }
            if($data->status == 3) {
                $dataDisplay['status'] = 'Declined';
            }
            $dataDisplay['car_id'] = $data->car_id;
            $dataDisplay['car_registration_no'] = $data->car_registration_no;
            $dataDisplay['co_id'] = $data->co_id;
            if($data->symbol != '') {
                $dataDisplay['currency'] = $data->symbol;
            } else {
                $dataDisplay['currency'] = 'R';
            }
            $wash_types = WashTypeToWash::select('wash_categories.wash_name', 'wash_type_to_washes.price')
                            ->join('wash_categories', 'wash_categories.id', '=', 'wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.prebooking_id', $data->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
            $dataDisplay['wash_types'] = $wash_types;

            $optionalExtra = OptionalExtra::where('prebooking_id', $data->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
            $dataDisplay['extras'] = $optionalExtra;
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'detail' => $dataDisplay
        ]);
    }

    public function accept(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');

        $record = PreBooking::find($prebooking_id);
        $record->status = 2;
        $record->save();

        $getCwo = CarWashOwner::where('id', $record->cwo_id)->select('cwo_company')->first();
        $cwo_company = $getCwo->cwo_company;
        $getCar = CarOwnerCar::where('id', $record->car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;
        $getCo = CarOwner::where('id', $record->co_id)->select('co_fname', 'co_lname', 'email', 'fcm_token')->first();
        if($record->name != '') {
            $recipient_name = $record->name;
        } else {
            $recipient_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $email = $getCo->email;
        $fcm_token = $getCo->fcm_token;

        $status_text = 'confirmed';

        /*send mail starts*/
        if($email != ''){
            $recipient_email = $email;
            // echo $recipient_email;exit;
            $subject = 'Autoclick Car Pre Booking Confirmed';
            $message_body = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking Confirmed</title>
                                </head>
                                <body>
                                    <p>Hi ' . $recipient_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been confirmed at  ' . $cwo_company . '. Thank you!</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';
            // echo $message_body;exit;
            $email = sendMail(array($recipient_name, $recipient_email), $message_body, $subject);
            // print_r($email);exit;
        }
        /*send mail ends*/

        /*push starts*/
        // $notification_title = 'Autoclick Car Pre Booking ' . ucfirst($status_text);
        // $notification_body = 'Pre booking for your car ' . $car_registration_no . ' has been confirmed at ' . $cwo_company;
        // // echo $notification_title . ' ->' . $notification_body;exit;
        // $data=array("request_type" => "notification");
        // sendFcmNotification($fcm_token, $notification_title, $notification_body, $data);
        /*push ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Pre booking has been confirmed'
        ]);
    }


}
