<?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\CurrencyMaster;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Config;
use Hash;
use Auth;

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

    public function index()
    {
    }

    public function add(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_type' => 'required',
                'co_id' => 'required',
                'name' => 'required',
                // 'isd_code' => 'required',
                // 'phone_no' => 'required',
                'date' => 'required',
                'time' => 'required',
                'address' => 'required',
                'car_id' => 'required',
                'body_type_id' => 'required',
                'cwo_id' => 'required',
                'wash_types' => 'required'
            ]
        );

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

        $prebooking_type = $request->input('prebooking_type');
        $co_id = $request->input('co_id');
        $name = $request->input('name');
        $isd_code = $request->input('isd_code');
        $phone_no = $request->input('phone_no');
        $date = $request->input('date');
        $time = $request->input('time');
        $address = $request->input('address');
        $car_id = $request->input('car_id');
        $body_type_id = $request->input('body_type_id');
        $cwo_id = $request->input('cwo_id');
        $dt = Carbon::now();

        if($body_type_id != ''){
            $getBodyType = BodyType::where('id', $body_type_id)->select('name')->first();
            $body_type = $getBodyType->name;
        } else {
            $body_type_id = 0;
            $body_type = '';
        }

        $wash_types = $request->input('wash_types');
        $amount = 0; 
        if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $amount = $amount + $getPrice->price;
                    } else {
                        $amount = $amount + 0;
                    }
                } // foreach ends
            } // if ends
        }
        $total_amount = $amount;

        /*insert into pre_bookings table starts*/
        $data = PreBooking::create([
            'prebooking_type'=> $prebooking_type,
            'co_id'=> $co_id,
            'name'=> $name,
            'isd_code'=> $isd_code,
            'phone_no'=> $phone_no,
            'date'=> $date,
            'time'=> $time,
            'date_time'=> $date . ' ' . $time,
            'address'=> $address,
            'car_id'=> $car_id,
            'body_type_id'=> $body_type_id,
            'body_type'=> $body_type,
            'cwo_id'=> $cwo_id,
            'amount'=> $amount,
            'total_amount'=> $total_amount,
            'status'=> 1,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        $prebooking_id = $data->id;
        /*insert into pre_bookings table ends*/

        if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $wash_type_price = $getPrice->price;
                    } else {
                        $wash_type_price = 0;
                    }
                    $assignWashType = WashTypeToPrebooking::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                } // foreach ends
            } // if ends
        }

        $getCwo = CarWashOwner::where('id', $cwo_id)->select('cwo_company', 'cwo_email', 'currency_id')->first();
        $cwo_company = $getCwo->cwo_company;
        $cwo_email = $getCwo->cwo_email;
        if($getCwo->currency_id != 0){
            $getCurrency = CurrencyMaster::findorfail($getCwo->currency_id);
            $currency = $getCurrency->symbol;
        } else {
            $currency = 'R';
        }

        $getCar = CarOwnerCar::where('id', $car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;

        $getCo = CarOwner::where('id', $co_id)->select('co_fname', 'co_lname', 'email')->first();
        if($name != '') {
            $co_name = $name;
        } else {
            $co_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $co_email = $getCo->email;

        /*send mail to CWO starts*/
        if($cwo_email != ''){
            $subject_cwo = 'Autoclick Car Pre Booking';
            $message_body_cwo = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $cwo_company . '</p>
                                    <p>A Pre booking has been added. Following are the Details.</p>
                                    <p>Car Registration No.: ' . $car_registration_no . '</p>
                                    <p>Body Type: ' . $body_type . '</p>
                                    <p>Name: ' . $name . '</p>
                                    <p>Phone: +' . $isd_code . $phone_no . '</p>
                                    <p>Date: ' . $date . '</p>
                                    <p>Time: ' . $time . '</p>
                                    <p>Adrees: ' . $address . '</p>
                                    <p>Total Amount: ' . $currency . $total_amount . '</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_cwo;exit;
            $email_cwo = sendMail(array($cwo_company, $cwo_email), $message_body_cwo, $subject_cwo);
            // print_r($email_cwo);exit;
        }
        /*send mail to CWO ends*/

        /*send mail to CO starts*/
        if($co_email != ''){
            $subject_co = 'Autoclick Car Pre Booking';
            $message_body_co = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $co_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been added at  ' . $cwo_company . '.  Following are the Details.</p>
                                    <p>CWO Company: ' . $cwo_company . '</p>
                                    <p>Car Registration No.: ' . $car_registration_no . '</p>
                                    <p>Body Type: ' . $body_type . '</p>
                                    <p>Name: ' . $name . '</p>
                                    <p>Phone: +' . $isd_code . $phone_no . '</p>
                                    <p>Date: ' . $date . '</p>
                                    <p>Time: ' . $time . '</p>
                                    <p>Adrees: ' . $address . '</p>
                                    <p>Total Amount: ' . $currency . $total_amount . '</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_co;exit;
            $email_co = sendMail(array($co_name, $co_email), $message_body_co, $subject_co);
            // print_r($email_co);exit;
        }
        /*send mail to CO ends*/

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

    }

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

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

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

        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;


        $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', 'cwo_master.cwo_company', 'cwo_master.address as cwo_address', 'cwo_master.cwo_isd', 'cwo_master.cwo_phone', 'cwo_master.cwo_email')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            // ->where('pre_bookings.co_id', $cwo_id)
            ->where(function($query) use ($co_phone, $co_id) {
                $query->where('pre_bookings.co_id', $co_id)
                    ->orWhere('pre_bookings.phone_no', $co_phone);
            });
        $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['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';
                }
                $dataDisplay['cwo_company'] = $d->cwo_company;
                $dataDisplay['cwo_address'] = $d->cwo_address;
                $dataDisplay['cwo_isd'] = $d->cwo_isd;
                $dataDisplay['cwo_phone'] = $d->cwo_phone;
                $dataDisplay['cwo_email'] = $d->cwo_email;

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

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


}
