<?php

namespace App\Http\Controllers\Api\Tms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Auth;

use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Models\Tms\Vehicle;
use App\Models\Tms\Vehicles\VehicleDocument;
use App\Models\Tms\Vehicles\VehicleInstallation;
use App\Models\Tms\BatteryStock;
use App\Models\Tms\BatteryHistory;
use App\Models\Tms\TyreStock;
use App\Models\Tms\TyreHistory;
use App\Models\Tms\Trailer;
use App\Models\Tms\Trailers\TrailerHistory;
use App\Models\Tms\RimStock;
use App\Models\Tms\RimHistory;
use App\Models\Item;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use App\Models\User\UserHistory;
use App\Imports\Tms\TyreImport;
use Maatwebsite\Excel\Facades\Excel;

use Illuminate\Support\Facades\Redirect;

class VehicleController extends Controller
{

    // vehicle Update
    public function vehicleCreateUpdate(Request $request){

        $validator = Validator::make($request->all(), [
            'vin_number' => 'required',
            'vehicle_id' => 'required',
            'registration_number' => 'required',
            'year' => 'required',
            'make' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ], 200);
        }

        $obj['vehicle_id'] = $request['vehicle_id'];
        $obj['make'] = $request['make'];
        $obj['model'] = $request['model'];
        $obj['year'] = $request['year'];
        $obj['vin_number'] = $request['vin_number'];
        $obj['registration_number'] = $request['registration_number'];  
        $obj['title_status'] = $request['title_status'];
        $obj['fuel_type'] = $request['fuel_type'];
        $obj['engine_type'] = $request['engine_type'];
        $obj['transmission_type'] = $request['transmission_type'];
        $obj['color'] = $request['color'];
        $obj['mileage'] = $request['mileage'];
        $obj['purchase_date'] = $request['purchase_date']?? Carbon::now()->format('Y-m-d');
        $obj['purchase_price'] = $request['purchase_price']??0;
        $obj['owner_name'] = $request['owner_name']?? null;
        $obj['owner_contact'] = $request['owner_contact']?? null;
        $obj['gps_device_id'] = $request['gps_device_id']?? null;
        $obj['vehicle_type'] = $request['vehicle_type']??null;
        $obj['axle_tyre_configuration'] = $request['axle_tyre_configuration']??null;
        $obj['no_of_wheels'] = $request['no_of_wheels']??0;
        $obj['axle_configuration'] = $request['axle_configuration']??null;
        $obj['vehicle_class'] = $request['vehicle_class']??null;
        $obj['license_renewal_date'] = $request['license_renewal_date']??null;
        $obj['emissions_testing_date'] = $request['emissions_testing_date']??null;
        $obj['emissions_compliance'] = $request['emissions_compliance']??null;
        $obj['notes_comments'] = $request['notes_comments']??null;
        $obj['qr_code'] = $request['qr_code']??null;
        $obj['json_data'] = $request['json_data']??null;
        $obj['is_logistics'] = $request['is_logistics']??0;
        $obj['logistic_provider_id'] = $request['logistic_provider_id']??0;


        if($request['id'] > 0){

            try {

                $vehicle = Vehicle::findOrFail($request['id']);
            
                $vehicle->update($obj);

                //Delete vehicle documents
                VehicleDocument::where('vehicle_id', $vehicle->id)->delete();

                //Create new documents
                 if($request['documents'] != null && count($request['documents']) > 0){

                    foreach($request['documents'] as $document){
                        VehicleDocument::create([
                            'vehicle_id' => $vehicle->id,
                            'document_name' => $document['document_name'],
                            'id_number' => $document['id_number'],
                            'issue_date' => $document['issue_date'],
                            'expiry_date' => $document['expiry_date'],
                            'renewal_date' => $document['renewal_date'],
                            'attachments' => $document['attachments'],
                            'remarks' => $document['remarks'],
                        ]);
                    }
                }

                return response()->json([
                    'success' => true,
                    'message' => 'Vehicle updated successfully',
                    'data' => $vehicle
                ], 200);

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Vehicle not found',
                    'data' => null
                ], 200);
            }
        } else {
            $vehicle = Vehicle::create($obj);

            // Creating Multiple documents
            if($request['documents'] != null && count($request['documents']) > 0){

                foreach($request['documents'] as $document){
                    VehicleDocument::create([
                        'vehicle_id' => $vehicle->id,
                        'document_name' => $document['document_name'],
                        'id_number' => $document['id_number'],
                        'issue_date' => $document['issue_date'],
                        'expiry_date' => $document['expiry_date'],
                        'renewal_date' => $document['renewal_date'],
                        'attachments' => $document['attachments'],
                        'remarks' => $document['remarks'],
                    ]);
                }
            }

            return response()->json([
                'success' => true,
                'message' => 'Vehicle created successfully',
                'data' => $vehicle
            ], 200);
        }
    }
  
    // Display a listing of the vehicles.    
    public function vehicleList(Request $request){

        $user=Auth::user();
        
        $vehicle=Vehicle::where('is_disabled',0)
            ->with('logistic_provider:id,display_name');

        if($request['logistic_provider_id']>0){
            $vehicle=$vehicle->where('logistic_provider_id',$request['logistic_provider_id']);
        }

        if(isset($request['is_logistics']) && $request['is_logistics']!=''){
            $vehicle=$vehicle->where('is_logistics',$request['is_logistics']);
        }

         if($request['is_megamarket']==1){
            $vehicle=$vehicle->where('is_logistics',0);
        }

        if($request['is_logistics']==1){
            $vehicle=$vehicle->where('is_logistics',1);
        }

        if($request['search']!=null && $request['search']!=''){

            $vehicle = $vehicle->where(function ($query) use ($request) {

                $query->where('vehicle_id', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('make', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('model', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('year', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('vin_number', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('registration_number', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('vehicle_type', 'LIKE', '%' . $request['search'] . '%');

            });
        }

        $count=$vehicle->count();

        $vehicle =$vehicle->orderBy('id','desc')
            ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
            ->get();

        $response=[
            'success'=>true,
            'total'=>$count,
            'data'=>$vehicle
        ];

        return response()->json($response);
    }

    //Updated Vehicle Detail
    public function vehicleDetails(Request $request)
    {
        try {
            // Validate the request
            $validator = Validator::make($request->all(), [
                'id' => 'required_without:vehicle_no',
                'vehicle_no' => 'required_without:id',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first(),
                    'data' => null
                ], 200);
            }

            // Fetch vehicle details based on which parameter was provided
            if ($request->has('id')) {
                $vehicle = Vehicle::with('battery', 'rim', 'tyre', 'stepney_tyre','documents',
                                        'stepney_rim', 'trailer', 'vehicle_installations','logistic_provider:id,display_name',
                                        'trailer.trailer.trailer_installations')
                            ->findOrFail($request->id);
            } else {
                $vehicle = Vehicle::with('battery', 'rim', 'tyre', 'stepney_tyre', 'documents',
                                        'stepney_rim', 'trailer', 'vehicle_installations','logistic_provider:id,display_name',
                                        'trailer.trailer.trailer_installations')
                            ->where('vehicle_id', $request->vehicle_no)
                            ->firstOrFail();
            }

            return response()->json([
                'success' => true,
                'message' => 'Vehicle details fetched successfully',
                'data' =>$vehicle
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Vehicle not found',
                'data' => null
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An unexpected error occurred',
                'error' => $e->getMessage(),
                'data' => null
            ], 200);
        }
    }


    // Vehicle Installation
    public function vehicleInstallation(Request $request)
    {
        // Validate the request
        $validator = Validator::make($request->all(), [
            'type_id' => 'required',
            'type' => 'required',       // Battery , Tyre , Rim , Stepney Tyre , Stepney Rim , Trailer
            'vehicle_id' => 'required',
            // 'position' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ], 200);
        }

        // Get the current date, time and user
        $date = date('Y-m-d');
        $time = date('H:i:s');
        $user = Auth::user();
        
         // Fetch vehicle details
        try {

            $vehicle = Vehicle::findOrFail($request->vehicle_id);

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Vehicle not found',
                'data' => null
            ], 200);
        }

        // Battery installation
        if($request->input('type') == 'battery') {

            try {

                $battery = BatteryStock::findOrFail($request->input('type_id'));

                // Update the battery stock record
                $battery->installation_date = $date;
                $battery->vehicle_id = $request->input('vehicle_id');
                $battery->location_status = 'Vehicle';
                $battery->position = $request->input('position');
                $battery->update();

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Battery not found',
                    'data' => null
                ], 200);
            }
            

            // Save the vehicle battery History record
            $history = new BatteryHistory;
            $history->battery_id = $battery->id;
            $history->date = $date;
            $history->moved_from = 'Store';
            $history->moved_to = 'Vehicle';
            $history->vehicle_id = $request->input('vehicle_id');
            $history->attachment = $request->input("attachment");
            $history->remark = 'Battery installed on vehicle ' . $vehicle['vehicle_id'] . ' at position ' . $request->input('position');
            $history->save();

        }

        // Tyre installation
        if($request->input('type') == 'tyre') {

            try {

                $tyre = TyreStock::findOrFail($request->input('type_id'));

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tyre not found',
                    'data' => null
                ], 200);
            }
            // Update the tyre stock record
            $tyre->installation_date = $date;
            $tyre->vehicle_id = $request->input('vehicle_id');
            $tyre->location_status = 'Vehicle';
            $tyre->position_on_vehicle = $request->input('position');
            $tyre->update();

            // Save the vehicle tyre History record
            $history = new TyreHistory;
            $history->tyre_id = $tyre->id;
            $history->date = $date;
            $history->moved_from = 'Store';
            $history->moved_to = 'Vehicle';
            $history->vehicle_id = $request->input('vehicle_id');
            $history->attachment = $request->input("attachment");
            $history->remark = 'Tyre installed on vehicle ' . $vehicle['vehicle_id'] . ' at position ' . $request->input('position');
            $history->save();

        }

        // Rim installation
        if($request->input('type') == 'rim') {

            try {

                $rim = RimStock::findOrFail($request->input('type_id'));

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Rim not found',
                    'data' => null
                ], 200);
            }
            // Update the rim stock record
            $rim->installation_date = $date;
            $rim->vehicle_id = $request->input('vehicle_id');
            $rim->location_status = 'Vehicle';
            $rim->position_on_vehicle = $request->input('position');
            $rim->update();

            // Save the vehicle rim History record
            $history = new RimHistory;
            $history->rim_id = $rim->id;
            $history->date = $date;
            $history->moved_from = 'Store';
            $history->moved_to = 'Vehicle';
            $history->vehicle_id = $request->input('vehicle_id');
            $history->attachment = $request->input("attachment");
            $history->remark = 'Rim installed on vehicle ' . $vehicle['vehicle_id'] . ' at position ' . $request->input('position');
            $history->save();

        }

        // Stepney Tyre installation
        if($request->input('type') == 'stepney_tyre') {

            try {

                $stepneyTyre = TyreStock::findOrFail($request->input('type_id'));

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Stepney Tyre not found',
                    'data' => null
                ], 404);
            }
            // Update the stepney tyre stock record
            $stepneyTyre->installation_date = $date;
            $stepneyTyre->vehicle_id = $request->input('vehicle_id');
            $stepneyTyre->location_status = 'Vehicle';
            $stepneyTyre->position_on_vehicle = $request->input('position');
            $stepneyTyre->update();

             // Save the vehicle tyre History record
            $history = new TyreHistory;
            $history->tyre_id = $tyre->id;
            $history->date = $date;
            $history->moved_from = 'Store';
            $history->moved_to = 'Vehicle';
            $history->vehicle_id = $request->input('vehicle_id');
            $history->attachment = $request->input("attachment");
            $history->remark = 'Added Stepney Tyre to vehicle with ID ' . $vehicle['vehicle_id'] . ' at position ' . $request->input('position');
            $history->save();

        }

        // Stepney Rim installation
        if($request->input('type') == 'stepney_rim') {

             try {

                $rim = RimStock::findOrFail($request->input('type_id'));

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Rim not found',
                    'data' => null
                ], 404);
            }
            // Update the rim stock record
            $rim->installation_date = $date;
            $rim->vehicle_id = $request->input('vehicle_id');
            $rim->location_status = 'Vehicle';
            $rim->position_on_vehicle = $request->input('position');
            $rim->update();

            // Save the vehicle rim History record
            $history = new RimHistory;
            $history->rim_id = $rim->id;
            $history->date = $date;
            $history->moved_from = 'Store';
            $history->moved_to = 'Vehicle';
            $history->vehicle_id = $request->input('vehicle_id');
            $history->attachment = $request->input("attachment");
            $history->remark = 'Stepney Rim installed on vehicle ' . $vehicle['vehicle_id'] . ' at position ' . $request->input('position');
            $history->save();
        }

        // Trailer installation
        if($request->input('type') == 'trailer') {

            try {

                $trailer = Trailer::findOrFail($request->input('type_id'));

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Trailer not found',
                    'data' => null
                ], 404);
            }
            // Update the trailer stock record
            $trailer->vehicle_id = $request->input('vehicle_id');
            $trailer->location_status = 'Vehicle';
            $trailer->update();

            // Save the vehicle tyre History record
            $history = new TrailerHistory;
            $history->trailer_id = $trailer->id;
            $history->date = $date;
            $history->action_type = 'Added';
            $history->vehicle_id = $request->input('vehicle_id');
            $history->remarks = 'Trailer Added to vehicle with ID ' . $vehicle['vehicle_id'];
            $history->save();

            $obj['trailer_configuration'] = $trailer->axle_configuration;
        }

        // Save the vehicle installation record         
        $obj['date'] = $date;
        $obj['vehicle_id'] = $request->input('vehicle_id');
        $obj['type'] = $request->input('type');
        $obj['type_id'] = $request->input('type_id');
        $obj['position'] = $request->input('position');
        
        $installation = VehicleInstallation::create($obj);

        $response = [
            'success' => true,
            'message' => ucfirst($request['type']) . ' Installation on Vehicle created successfully',
            'data' => $installation
        ];

        return response()->json($response, 200);

    }

    // Tyre installation on vehicle via Excle Sheet
    public function tyreInstallation(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file'
        ]);

        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ];
        }else{
            $file = $request->file('file');
            Excel::queueImport(new TyreImport, $file);

            $response=[
                'success'=>true,
                'message'=>'Tyres Installed on Vehicle Imported Successfully'
            ];

            return response()->json($response);
        }

    }

      //Save vehicle Tyre Configuration
    public function vehicleTyreConfiguration(Request $request)
    {
        // Validate the request
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'axle_tyre_configuration' => 'required',
        ]);

        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ];
        }

        // Fetch the vehicle
        try {
            $vehicle = Vehicle::findOrFail($request->id);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return [
                'success' => false,
                'message' => 'Vehicle not found',
                'data' => null
            ];
        }

        // Update the axle tyre configuration
        $vehicle->axle_tyre_configuration = $request->axle_tyre_configuration??null;
        $vehicle->save();

        return response()->json([
            'success' => true,
            'message' => 'Vehicle configuration updated successfully',
            'data' => $vehicle
        ], 200);
    }

     //Save Vehicle Axle Configuration
    public function vehicleAxleConfiguration(Request $request)
    {
        // Validate the request
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'axle_configuration' => 'required',
        ]);

        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ];
        }

        // Fetch the trailer
        try {
            $vehicle = Vehicle::findOrFail($request->id);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return [
                'success' => false,
                'message' => 'Vehicle not found',
                'data' => null
            ];
        }

        // Update the axle configuration
        $vehicle->axle_configuration = $request->axle_configuration??null;
        $vehicle->save();

        return response()->json([
            'success' => true,
            'message' => 'Vehicle Axle configuration updated successfully',
            'data' => $vehicle
        ], 200);
    }

    public function remove_trailer(Request $request)
    {
         // Validate the request
        $validator = Validator::make($request->all(), [
            'type_id' => 'required',  // Battery , Tyre , Rim , Stepney Tyre , Stepney Rim , Trailer
            'vehicle_id' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ], 422);
        }

        $date = date('Y-m-d');

        $vehicle_installation =  VehicleInstallation::where('type', 'trailer')
            ->where('vehicle_id', $request->input('vehicle_id'))
            ->where('type_id', $request->input('type_id'))
            ->where('rolled_back', 0)
            ->first();

        if( !$vehicle_installation) {
            return response()->json([
                'success' => false,
                'message' => 'Trailer not found',
                'data' => null
            ], 404);
        }

        // Updated trailer stock record
        $trailer= Trailer::where('id', $vehicle_installation->type_id)->first();
        $trailer->location_status = 'Store';
        $trailer->vehicle_id = '';
        $trailer->save();

        // Trailer installation record Delete
        $vehicle_installation->delete();

        // Save the vehicle tyre History record
        $history = new TrailerHistory;
        $history->trailer_id = $trailer->id;
        $history->date = $date;
        $history->action_type = 'Removed';
        $history->vehicle_id = $request->input('vehicle_id');
        $history->remarks = 'Trailer Removed from vehicle with ID ' . $request['vehicle_id'];
        $history->save();

        $response = [
            'success' => true,
            'message' => 'Trailer removed from vehicle successfully'
        ];

        return response()->json($response, 200);
    }

    //Vehicle Documents Create/Update
    public function vehicleDocumentCreateUpdate(Request $request)
    {
        // Validate the request
        $validator = Validator::make($request->all(), [
            'vehicle_id' => 'required',
            'document_name' => 'required',
            'id_number' => 'required',
        ]);

        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ];
        }

        // Save the vehicle document record
        $obj['vehicle_id'] = $request->input('vehicle_id');
        $obj['document_name'] = $request->input('document_name');
        $obj['id_number'] = $request->input('id_number');
        $obj['issue_date'] = $request->input('issue_date');
        $obj['expiry_date'] = $request->input('expiry_date');
        $obj['renewal_date'] = $request->input('renewal_date');
        $obj['attachments'] = $request->input('attachments');
        $obj['remarks'] = $request->input('remarks');

        // Updating the vehicle document
        if($request['id']>0){
            $vehicle_document = VehicleDocument::find($request['id']);

            if ($vehicle_document) {
                $vehicle_document->update($obj);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Vehicle Document not found',
                    'data' => null
                ], 404);
            }
        }else{
            $vehicle_document = VehicleDocument::create($obj);
        }

        $response = [
            'success' => true,
            'message' => $request['id']>0 ? 'Vehicle Document updated successfully' : 'Vehicle Document created successfully',
            'data' => $vehicle_document
        ];

        return response()->json($response, 200);
    }

    // View Vehicle Documents list
    public function vehicleDocumentsList(Request $request)
    {
         // Validate the request
        $validator = Validator::make($request->all(), [
            'vehicle_id' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ], 422);
        }

        $vehicle_document = VehicleDocument::where('vehicle_id', $request->input('vehicle_id'))->get();

        if ($vehicle_document) {
            return response()->json([
                'success' => true,
                'message' => 'Vehicle Document fetched successfully',
                'data' => $vehicle_document
            ], 200);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'No documents found for this vehicle',
                'data' => null
            ], 404);
        }
    }

    // View Vehicle Document details
    public function vehicleDocumentDetails(Request $request)
    {
        // Validate the request
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ], 422);
        }

        // Fetch vehicle document details
        try {
            $vehicle_document = VehicleDocument::findOrFail($request->id);

            return response()->json([
                'success' => true,
                'message' => 'Vehicle Document details fetched successfully',
                'data' =>$vehicle_document
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Vehicle Document not found',
                'data' => null
            ], 404);
        }
    }

    public function qr_gn(Request $request)
    {

        $vehicles = Vehicles::all();
        foreach ($vehicles as $data) {

            $vehicleId = $data->vehicle_id;
            QrCode::size(200)->format('png')->margin(2)->generate($vehicleId, public_path('uploads/' . $vehicleId . '.png'));
            $qrCode = $vehicleId . '.png';

            $vehicle = Vehicles::where('vehicle_id', $vehicleId)->first();
            $vehicle->qr_code = $qrCode;
            $vehicle->save();
        }
    }

    public function download_qr($id)
    {
        $image = Vehicles::findOrFail($id);
        $pathToFile = public_path('uploads/' . $image->qr_code);
        // $pathToFile = url('uploads/' . $image->qr_code);


        if ($image->qr_code != '') {
        return response()->download($pathToFile);
        } else {
        session()->flash('success', 'QR Code does not exist.');
        return redirect()->back();
        }



        // $pathToFile = storage_path('app/public/documents/document.pdf');
        // $headers = [
        //     'Content-Type' => 'application/pdf',
        // ];
        // return response()->download($pathToFile, 'document.pdf', $headers);
    }

    //Getting all the vehicles of the logistics provider
}
