<?php

namespace App\Http\Controllers\OwnerPanel;

use App\Http\Controllers\Controller;
// use App\Services\CarSearchService;
use Illuminate\Http\Request;
use App\Models\OtherServiceReport;
use App\Models\OtherServiceReportToProduct;
use App\Models\OtherService;
use Carbon\Carbon;
use DB;
use Auth;

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

    public function index(Request $request)
    {
        // echo "search car";exit;
        $cwo_id = Auth::user()->cwo_id;
        $dataBag = array();
        $dataBag['chMenu'] = 'otherServiceReportList';
        // $car_registration_no = $request->input('car_registration_no');
        $start_date = $request->input('start_date');
        if($start_date != ''){
            $start_date = date("Y-m-d", strtotime($start_date));
        }
        $end_date = $request->input('end_date');
        if($end_date != ''){
            $end_date = date("Y-m-d", strtotime($end_date));
        }
            $data = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time')
            ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->orderBy('other_service_reports.id', 'desc');
        // if ($car_registration_no != '') {
        //     $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
        // }   
        if($start_date != '') {
            $data->whereDate('other_service_reports.date', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('other_service_reports.date', '<=', $end_date);
        }    

        $dataCnt = $data->count();
        $data = $data->paginate(10);
        $dataBag['allRecords'] = $dataCnt;
        $dataBag['records'] = $data;
        // echo "<pre>";print_r($dataBag['records']->toArray());exit;
        return view('owner.otherservicesreport.list', $dataBag);
    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function download(Request $request)
    {
        $cwo_id = Auth::user()->cwo_id;
        $fileName = 'other-services-products-report.csv';

        // $car_registration_no = $request->input('car_registration_no');
        $start_date = $request->input('start_date');
        if($start_date != ''){
            $start_date = date("Y-m-d", strtotime($start_date));
        }
        $end_date = $request->input('end_date');
        if($end_date != ''){
            $end_date = date("Y-m-d", strtotime($end_date));
        }
            $data = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time')
            ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->orderBy('other_service_reports.id', 'desc');
        // if ($car_registration_no != '') {
        //     $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
        // }   
        if($start_date != '') {
            $data->whereDate('other_service_reports.date', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('other_service_reports.date', '<=', $end_date);
        }     

        $data = $data->get();

        $headers = array(
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        );
        $columns = array('Sl #', 'Logged in User', 'Client Name', 'Client Phone', 'Products/Services', 'Amount(R)', 'Date', 'Time', 'Payment Status', 'Payment Type');

        $callback = function () use ($data, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            $i = 1;
            foreach ($data as $d) {
                if(Auth::user()->email != ''){
                    $row['logged_in_user'] = Auth::user()->name . ' - ' . Auth::user()->email;
                } else {
                    $row['logged_in_user'] = Auth::user()->name;
                }

                if($d->email != '') {
                    $row['name'] = $d->name . ' - ' . $d->email;
                } else {
                    $row['name'] = $d->name;
                }

                if($d->phone != ''){
                    $row['phone'] = '+' . $d->isd_code . $d->phone;
                } else {
                    $row['phone']  = '';
                }
                $row['amount']  = $d->total_amount;
                $row['services'] = getOtherServices($d->id);
                if ($d->date != '') {
                    $row['date']  = date("Y/m/d", strtotime($d->date));
                } else {
                    $row['date'] = '';
                }
                if ($d->time != '') {
                    $row['time']  = date("H:i", strtotime($d->time));
                } else {
                    $row['time'] = '';
                }
                if ($d->payment_status == 1) {
                    $row['payment_status']  = 'Paid';
                } else {
                    $row['payment_status']  = 'Not Paid';
                }
                $row['payment_details']  = $d->payment_details;

                fputcsv($file, array($i++, $row['logged_in_user'], $row['name'], $row['phone'], $row['services'], $row['amount'], $row['date'], $row['time'], $row['payment_status'], $row['payment_details']));
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    public function printDetail($id)
    {
        $data = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time', 'cwo_master.cwo_logo')
        ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
        ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('other_service_reports.id', $id);
        $data = $data->get();
        // echo "<pre>";print_r($data->toArray());exit;
        $dataBag['id'] = $data[0]->id;
        if($data[0]->name != ''){
            $dataBag['name'] = $data[0]->name;
        } else {
            $dataBag['name'] = '';
        }
        if($data[0]->phone != ''){
            $dataBag['phone'] = '+' . $data[0]->isd_code . $data[0]->phone;
        } else {
            $dataBag['phone'] = '';
        }
        if($data[0]->date != '') {
            $dataBag['date']  = date("d/m/Y", strtotime($data[0]->date));
        } else {
            $dataBag['date']  = '';
        }
        if($data[0]->time != '') {
            $dataBag['time']  = date("h:i a", strtotime($data[0]->time));
        } else {
            $dataBag['time']  = '';
        }
        $dataBag['payment_status_id'] = $data[0]->payment_status;
        if($data[0]->payment_status == 1) {
            $dataBag['payment_status'] = 'Paid';
        } else {
            $dataBag['payment_status'] = 'Not Paid';
        }
        $dataBag['payment_mode'] = $data[0]->payment_details;
        $dataBag['total_amount'] = $data[0]->total_amount;

        if($data[0]->cwo_logo != ''){
            $dataBag['cwo_logo'] = asset('images/cwo') . '/' . $data[0]->cwo_logo;
        } else {
            $dataBag['cwo_logo'] = '';
        }

        // $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.wash_id', $data[0]->id)
        //                     ->orderBy('wash_type_to_washes.id', 'asc')
        //                     ->get();
        $services = DB::table('other_service_report_to_products')->select('other_services.description', 'other_service_report_to_products.price', 'other_service_report_to_products.quantity', 'other_service_report_to_products.total_price')
                ->join('other_service_reports', 'other_service_report_to_products.other_service_report_id', 'other_service_reports.id')
                ->join('other_services', 'other_service_report_to_products.other_service_id', 'other_services.id')
                ->where('other_service_report_to_products.other_service_report_id', $data[0]->id)
                ->orderBy('other_service_report_to_products.id', 'asc')
                ->get();                   
        $dataBag['services'] = $services;

        // echo "<pre>";print_r($dataBag);exit;
        return view('owner.otherservicesreport.print', $dataBag);
    }

    public function delete($id)
    {
        $record = OtherServiceReport::find($id); // fetch the record
        $record->delete();

        $serviceReportToProduct = OtherServiceReportToProduct::where('other_service_report_id', $id);
        $serviceReportToProduct->delete();

        return back()->with('msg', 'This record has been deleted successfully.')
            ->with('msg_class', 'alert alert-success');
    }

    public function edit($id)
    {
        $cwo_id = Auth::user()->cwo_id;
        $record = OtherServiceReport::find($id); // fetch the record
        // echo "other_service_report_id-> " . $id . ", cwo_id-> " . $record->cwo_id;exit; 
        $dataBag['details'] = $record;
        // echo "<pre>";print_r($dataBag['details']);exit;

        $data = OtherService::where('cwo_id', $cwo_id)->where('is_active', 1)->orderBy('description', 'asc')->get();
        $dataBag['otherServices'] = $data;
        $dataDisplay=[];
        $dataArray = [];
        // echo "<pre>";print_r($data->toArray());exit;
        if($data != ''){
            foreach ($data as $d) {
                $dataDisplay['service_id'] = $d->id;
                $dataDisplay['service'] = $d->description;
                $dataDisplay['price'] = $d->price;
                $dataDisplay['qty_in_stock_applicable'] = $d->qty_in_stock_applicable;
                if($d->quantity != ''){
                    $dataDisplay['quantity_in_stock'] = $d->quantity;
                } else {
                    $dataDisplay['quantity_in_stock'] = '';
                }
                $getPr = OtherServiceReportToProduct::where('other_service_report_id', $id)->where('other_service_id', $d->id)->get();
                $dataDisplay['exists'] = $getPr->toArray();
                $dataArray[] = $dataDisplay;
            }
        }
        // echo "<pre>";print_r($dataArray);exit;
        $dataBag['dataArray'] = $dataArray;

        $existingServicesArray = array();
        $getExistingService = OtherServiceReportToProduct::where('other_service_report_id', $id)->select('other_service_id')->get();
        if($getExistingService != ''){
            foreach($getExistingService as $w)
            array_push($existingServicesArray, $w->other_service_id);
        }
        $dataBag['existingServicesArray'] = $existingServicesArray;
        // echo "<pre>";print_r($existingServicesArray);exit;

        return view('owner.otherservicesreport.edit', $dataBag); 
    }

    public function update(Request $request, $id)
    {
        // echo $id;exit;
        $request->validate([
            'service_id' => 'required',
            // 'optional_extra_price' => 'numeric|nullable',
            // 'name' => 'required',
            // 'car_registration_no' => 'required|unique:co_car,car_registration_no,' . $request->input('car_id'),
        ], [
            'service_id.required' => 'Please choose atleast one service.',
            // 'name.required' => 'Please enter a driver name.',
            // 'car_registration_no.unique' => 'This car registration number already exists.'
        ]);
        $service_id = $request->input('service_id');
        // echo "<pre>";print_r($service_id);
        $price = $request->input('price');
        // echo "<pre>";print_r($price);
        $quantity = $request->input('quantity');
        // echo "<pre>";print_r($quantity);
        $other_service_report_id = $id;

        $name = $request->input('name');
        if($name == ''){
            $name = 'Annonymous';
        }
        $email = $request->input('email');
        $isd_code = $request->input('isd_code');
        $phone = $request->input('phone');

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

        $dt = Carbon::now();

        $data = OtherServiceReport::findOrFail($id);

        $amount = 0; 
        $total_amount = 0; 

        DB::delete("DELETE FROM `other_service_report_to_products` WHERE `other_service_report_id` = " . $other_service_report_id . "");
        if (count($service_id) > 0) {
            for ($i = 0; $i < count($service_id); $i++) {
                // echo $service_id[$i] . ' - ' . $price[$i] . ' - ' . $quantity[$i] . ' - ' .   '<br>';
                // $getPrice = WashCategoryBodyType::where('servic '<br>';
                $getPrice = OtherService::where('id', $service_id[$i])->first();
                $service_price = $getPrice->price;
                // echo $service_id[$i] . ' - ' . $service_price . ' - ' . $quantity[$i] . ' - ' .   '<br>';

                // $total_price = $price[$i] * $quantity[$i];
                $total_price = $service_price * $quantity[$i];
                // echo 'total price -> ' . $total_price . "<br>";
                $total_amount = $total_amount + $total_price;

                $assignServices = OtherServiceReportToProduct::create([
                        'other_service_report_id'=> $other_service_report_id,
                        'other_service_id'=> $service_id[$i],
                        'price'=> $price[$i],
                        'quantity'=> $quantity[$i],
                        'total_price'=> $price[$i] * $quantity[$i],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);

                if($getPrice->qty_in_stock_applicable == 1) {
                    $remaining_quantity = $getPrice->quantity - $quantity[$i];
                    $getPrice->quantity = $remaining_quantity;
                    $getPrice->save();
                }



            } // foreach ends
        }
        // echo 'total amount-> ' . $total_amount;exit;
        $data->update([
            'total_amount' => $total_amount
        ]);
        // exit;

        $data->update([
            'name' => $name,
            'email' => $email,
            'isd_code' => $isd_code,
            'phone' => $phone
        ]);

        if($payment_status == 1){
            $data->update([
                'payment_status' => $payment_status
            ]);    
        }


        return back()->with('success', 'Other Services record has been updated successfully.')->with('msg_class', 'alert alert-success');
    }

    public function multiDelete(Request $request)
    {
        $delete_ids = $request->delete_ids;
        // echo "<pre>";print_r($delete_ids);exit;
        if($delete_ids != ''){
            $myArray = explode(',', $delete_ids);
            foreach ($myArray as $id) {
                $record = OtherServiceReport::find($id); // fetch the record
                $record->delete();

                $serviceReportToProduct = OtherServiceReportToProduct::where('other_service_report_id', $id);
                $serviceReportToProduct->delete();
            }
        }
        return response()->json(['message' => 'This record have been deleted successfully', 'status' => 1], 200);
    }

    public function quantityCheck(Request $request)
    {
        $service_id = $request->service_id;
        $quantity = $request->quantity;

        $record = OtherService::findorfail($service_id);
        $qty_in_stock_applicable = $record->qty_in_stock_applicable;
        $quantity_in_stock = $record->quantity;

        if($qty_in_stock_applicable == 1){
            if($quantity_in_stock >= $quantity){
                $status = 1;
                $message = 'success';
            } else {
                $status = 0;
                $message = 'Quantity should be within ' . $quantity_in_stock;
            }
        } else {
            $status = 1;
            $message = 'success';
        }


        // if($delete_ids != ''){
        //     $myArray = explode(',', $delete_ids);
        //     foreach ($myArray as $id) {
        //         $record = OtherServiceReport::find($id); // fetch the record
        //         $record->delete();

        //         $serviceReportToProduct = OtherServiceReportToProduct::where('other_service_report_id', $id);
        //         $serviceReportToProduct->delete();
        //     }
        // }
        return response()->json(['message' => $message, 'status' => $status], 200);
    }

}
