<?php

namespace App\Http\Controllers\Api\Tms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tms\TyreDetail;
use App\Models\Tms\TyreStock;
use App\Models\Tms\TyreHistory;
use App\Models\Tms\TyreServiceHistory;
use App\Models\Tms\TyreInspectionHistory;
use App\Models\Tms\Vehicles\VehicleInstallation;
use App\Models\Tms\Trailers\TrailerInstallation;
use App\Models\Item;
use Validator;
use Auth;
use Carbon\Carbon;
use App\Service\StockEntryService;

class TyreController extends Controller
{
    public function tyreList(Request $request)
    {
        $tyre_details = TyreDetail::whereHas('item', function ($query) {
            $query->where('tms_store','>',0);
        })->with('item:id,tms_store');

        // Apply filters if provided
        if ($request->has('brand') && $request->input('brand') != '') {
            $tyre_details->where('brand', 'like', '%' . $request->input('brand') . '%');
        }
        if ($request->has('model') && $request->input('model') != '') {
            $tyreStock->where('model', 'like', '%' . $request->input('model') . '%');
        }

        if ($request->has('tread_depth') && $request->input('tread_depth') != '') {
            $tyreStock->where('tread_depth',$request->input('tread_depth'));
        }

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

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

                $query->where('name', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('identity', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('brand', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('model', 'LIKE', '%' . $request['search'] . '%');
            });
        }
    
        $count = $tyre_details->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $tyre_details = $tyre_details->orderby($request['sort_by'],$sort_order);

        }else{
            $tyre_details = $tyre_details->orderby('id','desc');
        }

        $tyre_details= $tyre_details->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->get();

        return response()->json([
            'success' => true,
            'message' => 'Tyre list retrieved successfully',
            'total' => $count,
            'data' => $tyre_details
        ], 200);
    }

    // Creating Tyre Stock
    public function tyreStockCreate(Request $request)
    {
        $validator = validator($request->all(), [
            'tyre_id' => 'required',
            'tyre_detail_id' => 'required',
            'item_id' => 'required',
        ]);
    
        if ($validator->fails()) {
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        }
    
        // Check if the tyre Id already exists
        $existingTyre = TyreStock::where('tyre_id', $request['tyre_id'])->first();
        if ($existingTyre) {
            return [
                'success' => false,
                'message' => 'Tyre with ID already exists',
                'data' => $existingTyre
            ];
        }

        // Check if the Tyre stock is there in TMS Store
        $itemStock = Item::where('id', $request['item_id'])->first();
        if($itemStock==null){
            if($itemStock['tms_store']<=0 || $itemStock['tms_store']==null){
                return [
                    'success' => false,
                    'message' => 'Not Available in TMS Store, First Receive the Item in Store',
                    'data' => null
                ];
            }
        }
    
        $obj = [    
            'tyre_id' => $request['tyre_id'],
            'tyre_detail_id' => $request['tyre_detail_id'] ?? 0,
            'item_id' => $request['item_id'] ?? 0,
            'brand' => $request['brand'] ?? null,
            'model' => $request['model'] ?? null,
            'size' => $request['size'] ?? null,
            'tread_depth' => $request['tread_depth'] ?? null,
            'max_tread_depth' => $request['max_tread_depth'] ?? null,
            'rolling_km' => $request['rolling_km'] ?? 0,
            'max_rolling_km' => $request['max_rolling_km'] ?? 0,
            'purchase_date' => $request['purchase_date'] ?? null,
            'purchase_cost' => $request['purchase_cost'] ?? 0,
            'installation_date' => $request['installation_date'] ?? null,
            'vehicle_id' => $request['vehicle_id'] ?? 0,
            'position_on_vehicle' => $request['position_on_vehicle'] ?? null,
            'current_mileage' => $request['current_mileage'] ?? 0,
            'tire_condition' => $request['tire_condition'] ?? 'Good',
            'inflation_pressure' => $request['inflation_pressure'] ?? null,
            'temperature' => $request['temperature'] ?? 0,
            'load_rating' => $request['load_rating'] ?? null,
            'speed_rating' => $request['speed_rating'] ?? null,
            'dot_number' => $request['dot_number'] ?? null,
            'status' => $request['status'] ?? 'Active',
            'odometer_value' => $request['odometer_value'] ?? 0,
            'warranty_type' => $request['warranty_type'] ?? null,
            'warranty_start_date' => $request['warranty_start_date'] ?? null,
            'warranty_end_date' => $request['warranty_end_date'] ?? null,
            'notes_comments' => $request['notes_comments'] ?? null,
            'commercial_name' => $request['commercial_name'] ?? null,
            'identity' => $request['identity'] ?? null,
            'load_pressure_information' => $request['load_pressure_information'] ?? null,
            'indicated_exterior' => $request['indicated_exterior'] ?? null,
            'type_of_construction' => $request['type_of_construction'] ?? null,
            'tyre_sections_width_mm' => $request['tyre_sections_width_mm'] ?? 0,
            'section_height_to_section_width_ratio' => $request['section_height_to_section_width_ratio'] ?? 0,
            'rim_diameter_inches' => $request['rim_diameter_inches'] ?? 0,
            'load_capacity_index' => $request['load_capacity_index'] ?? null,
            'tyre_type' => $request['tyre_type'] ?? null,
            'remarks' => $request['remarks'] ?? null,
            'location_status' => $request['location_status'] ?? 'Store',
            'preferred_vehicles' => $request['preferred_vehicles'] ?? null,
        ];
    
        $tyreStock = TyreStock::create($obj);

        $tyreStock['description']="Tyre Stock with tyre id: ".$tyreStock['tyre_id']." moved to TMS store";

        // Update TMS Store
        $itemStock->tms_store = $itemStock->tms_store - 1;
        $itemStock->update();

        //Tyre history Create
        $obj1['tyre_id'] = $tyreStock['id']; // required – no default  //From the Tyre Stock lIst
        $obj1['date'] = Carbon::now()->toDate('Y-m-d');
        $obj1['moved_to'] = 'Tms Store';
        $obj1['moved_from'] = 'Store'; // From the Tyre Stock List
        $obj1['vehicle_id'] = $request['vehicle_id'] ?? 0;
        $obj1['remark'] = 'Tyre with Tyre Id: '.$tyreStock['tyre_id'].' moved to TMS Store';
        $obj1['attachment'] = $request['attachment'] ?? null;

        $tyreHistory = TyreHistory::create($obj1);
        
        return response()->json([
            'success' => true,
            'message' => 'Tyre stock created successfully',
            'data' => $tyreStock
        ], 200);
    }
    

    // Getting Stock Lists of Tyre
    public function tyreStockList(Request $request)
    {
        $tyreStock = TyreStock::query();

        // Apply filters if provide
    
        if (isset($request['location_status']) && $request->input('location_status') != '') {
            $tyreStock->where('location_status', $request->input('location_status'));
        }

        if(isset($request['tread_depth']) && $request->input('tread_depth') != '') {
            $tyreStock->where('tread_depth', $request->input('tread_depth'));
        }

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

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

                $query->where('tyre_id', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('commercial_name', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('brand', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('model', 'LIKE', '%' . $request['search'] . '%')
                ->orWhere('tyre_type', 'LIKE', '%' . $request['search'] . '%');
            });
        }

        $count = $tyreStock->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $tyreStock = $tyreStock->orderby($request['sort_by'],$sort_order);

        }else{
            $tyreStock = $tyreStock->orderby('id','desc');
        }

        $tyreStock= $tyreStock->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->get();

        return response()->json([
            'success' => true,
            'message' => 'Tyre stock list retrieved successfully',
            'total' => $count,
            'data' => $tyreStock
        ], 200);
    }

    // Tyre Stock Detail
    public function tyreStockDetail(Request $request)
    {
        $validator = validator($request->all(), [
            'tyre_stock_id' => 'required',
        ]);
    
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];
        }
        $tyreStock = TyreStock::where('id', $request['tyre_stock_id'])
            ->with('trailer','trailer.trailer_installations','vehicle','vehicle.vehicle_installations','vehicle.trailer')
            ->first();

        $tyre_inspection_history = TyreInspectionHistory::where('tyre_id', $request['tyre_stock_id'])
            ->orderBy('id', 'desc')    
            ->first();

        if (!$tyreStock) {
            return [
                'success' => false,
                'message' => 'Tyre not found',
                'data' => null
            ];
        }

        return response()->json([
            'success' => true,
            'message' => 'Tyre stock detail retrieved successfully',
            'data' => $tyreStock,
            'tyre_inspection_history' => $tyre_inspection_history
        ], 200);
    }


    // Tyre Move History Create
    public function tyreHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'tyre_id'=>'required',
            'date'=>'required|date',
            'moved_to'=>'required',
            'remark'=>'nullable|string',
        ]);

        if ($validator->fails()) {

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            //check if the tyre exists
            $tyreStock = TyreStock::where('id', $request['tyre_id'])->first();
            if (!$tyreStock) {
                return [
                    'success' => false,
                    'message' => 'Tyre not found',
                    'data' => null
                ];
            }

             if($tyreStock->vehicle_id > 0){

                $vehicle_installation = VehicleInstallation::where('type', 'tyre')->where('vehicle_id', $tyreStock->vehicle_id)
                ->where('type_id', $tyreStock->id)
                ->update([
                    'rolled_back' => 1
                ]);

                $tyreStock['installation_date']=null;
                $tyreStock['vehicle_id']=0;
                $tyreStock['position_on_vehicle']=null;

            }

            if($tyreStock->trailer_id > 0){ 

                $trailer_installation = TrailerInstallation::where('type', 'tyre')->where('trailer_id', $tyreStock->trailer_id)
                    ->where('type_id', $tyreStock->id)
                    ->update([
                        'rolled_back' => 1
                    ]);

                $tyreStock['installation_date']=null;
                $tyreStock['trailer_id']=0;
                $tyreStock['position_on_trailer']=null;

            }

            $obj['tyre_id'] = $request['tyre_id']; // required – no default  //From the Tyre Stock lIst
            $obj['date'] = $request['date']; // required – no default
            $obj['moved_to'] = $request['moved_to'] ?? null;
            $obj['moved_from'] = $tyreStock['location_status'] ?? null; // From the Tyre Stock List
            $obj['vehicle_id'] = $request['vehicle_id'] ?? 0;
            $obj['remark'] = $request['remark'] ?? null;
            $obj['attachment'] = $request['attachment'] ?? null;

            $tyreHistory = TyreHistory::create($obj);

            // Update the tyre stock location status
            $tyreStock->location_status = $request['moved_to'];
            $tyreStock->save();

            return response()->json([
                'success' => true,
                'message' => 'Tyre moved successfully',
                'data' => $tyreHistory
            ], 201);
        }
    }

    // Tyre Move History List
    public function tyreHistoryList(Request $request)
    {
        $tyreHistory = TyreHistory::query();

        // Apply filters if provided
        if ($request->has('tyre_id') && $request->input('tyre_id') != '') {
            $tyreHistory->where('tyre_id', $request->input('tyre_id'));
        }
        if ($request->has('date') && $request->input('date') != '') {
            $tyreHistory->where('date', $request->input('date'));
        }
        if ($request->has('moved_to') && $request->input('moved_to') != '') {
            $tyreHistory->where('moved_to', 'like', '%' . $request->input('moved_to') . '%');
        }
        if ($request->has('vehicle_id') && $request->input('vehicle_id') != '') {
            $tyreHistory->where('vehicle_id', $request->input('vehicle_id'));
        }
        if ($request->has('moved_from') && $request->input('moved_from') != '') {
            $tyreHistory->where('moved_from', 'like', '%' . $request->input('moved_from') . '%');
        }

        $count = $tyreHistory->count();
        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $tyreHistory = $tyreHistory->orderby($request['sort_by'],$sort_order);
        }else{
            $tyreHistory = $tyreHistory->orderby('id','desc');
        }
        $tyreHistory= $tyreHistory->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->get();

        return response()->json([
            'success' => true,
            'message' => 'Tyre history list retrieved successfully',
            'total' => $count,
            'data' => $tyreHistory
        ], 200);
    }
  
    // Tyre Service History Create
    public function tyreServiceHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'tyre_id'=>'required',
            'service_date'=>'required|date',
            'service_type'=>'required',
            'cost'=>'required|numeric',
            'description'=>'nullable|string',
        ]);

        if ($validator->fails()) {

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            //check if the tyre exists
            $tyreStock = TyreStock::where('id', $request['tyre_id'])->first();
            if (!$tyreStock) {
                return [
                    'success' => false,
                    'message' => 'Tyre not found',
                    'data' => null
                ];
            }

            $obj['tyre_id'] = $request['tyre_id']; // required – no default  //From the Tyre Stock lIst
            $obj['service_date'] = $request['service_date']??null; // required – no default
            $obj['service_type'] = $request['service_type'] ?? 0;
            $obj['cost'] = $request['cost'] ?? 0.0;
            $obj['description'] = $request['description'] ?? null;
            $obj['attachment'] = $request['attachment'] ?? null;

            $tyreHistory = TyreServiceHistory::create($obj);

            return response()->json([
                'success' => true,
                'message' => 'Tyre service history created successfully',
                'data' => $tyreHistory
            ], 201);
        }
    }
  
    // Tyre Service History List
    public function tyreServiceHistoryList(Request $request)
    {
        $tyreHistory = TyreServiceHistory::query();

        // Apply filters if provided
        if ($request->has('tyre_id') && $request->input('tyre_id') != '') {
            $tyreHistory->where('tyre_id', $request->input('tyre_id'));
        }
        if ($request->has('date') && $request->input('date') != '') {
            $tyreHistory->where('service_date', $request->input('date'));
        }
        if ($request->has('service_type') && $request->input('service_type') != '') {
            $tyreHistory->where('service_type', 'like', '%' . $request->input('service_type') . '%');
        }
        if ($request->has('vehicle_id') && $request->input('vehicle_id') != '') {
            $tyreHistory->where('vehicle_id', $request->input('vehicle_id'));
        }
        if ($request->has('remark') && $request->input('remark') != '') {
            $tyreHistory->where('remark', 'like', '%' . $request->input('remark') . '%');
        }

        $count = $tyreHistory->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $tyreHistory = $tyreHistory->orderby($request['sort_by'],$sort_order);
        }else{
            $tyreHistory = $tyreHistory->orderby('id','desc');
        }
        $tyreHistory= $tyreHistory->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->get();

        return response()->json([
            'success' => true,
            'message' => 'Tyre service history list retrieved successfully',
            'total' => $count,
            'data' => $tyreHistory
        ], 200);
    }

    // Tyre Inspection History Create
    public function tyreInspectionHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'tyre_id'=>'required',
            'inspection_date'=>'required|date',
            'inspection_user'=>'required',
            'description'=>'nullable|string',
        ]);

        if ($validator->fails()) {

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            //check if the tyre exists
            $tyreStock = TyreStock::where('id', $request['tyre_id'])->first();
            if (!$tyreStock) {
                return [
                    'success' => false,
                    'message' => 'Tyre not found In the Stock List',
                    'data' => null
                ];
            }

            $obj['tyre_id'] = $request['tyre_id']; // required – no default  //From the Tyre Stock lIst
            $obj['inspection_date'] = $request['inspection_date']??null; // required – no default
            $obj['inspection_user'] = $request['inspection_user'] ?? 0;
            $obj['tread_depth_mm'] = $request['tread_depth_mm'] ?? null;
            $obj['pressure'] = $request['pressure'] ?? null;
            $obj['current_rolling_km'] = $request['current_rolling_km'] ?? 0.0;
            $obj['faq'] = $request['faq'] ?? null;
            $obj['tyre_condition'] = $request['tyre_condition'] ?? null;
            $obj['action_type'] = $request['action_type'] ?? null;
            $obj['description'] = $request['description'] ?? null;
            $obj['attachment'] = $request['attachment'] ?? null;
            $obj['json_data'] = $request['json_data'] ?? null;

            $tyreHistory = TyreInspectionHistory::create($obj);

            if(isset($request['tread_depth_mm']) && $request['tread_depth_mm']!='' && $request['tread_depth_mm']!=null){
                TyreStock::where('id', $request['tyre_id'])->update(['tread_depth' => $request['tread_depth_mm']]);
                // TyreDetail::where('id', $request['tyre_id'])->update(['tread_depth_mm' => $request['tread_depth_mm']]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Tyre inspection history created successfully',
                'data' => $tyreHistory
            ], 201);
        }
    }
    
    // Tyre Inspection History List
    public function tyreInspectionHistoryList(Request $request)
    {
        $tyreHistory = TyreInspectionHistory::query();

        // Apply filters if provided
        if ($request->has('tyre_id') && $request->input('tyre_id') != '') {
            $tyreHistory->where('tyre_id', $request->input('tyre_id'));

        }
        if ($request->has('inspection_date') && $request->input('inspection_date') != '') {
            $tyreHistory->where('inspection_date', $request->input('inspection_date'));
        }
       
        if ($request->has('description') && $request->input('description') != '') {
            $tyreHistory->where('description', 'like', '%' . $request->input('description') . '%');
        }

        $count = $tyreHistory->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $tyreHistory = $tyreHistory->orderby($request['sort_by'],$sort_order);
        }else{
            $tyreHistory = $tyreHistory->orderby('id','desc');
        }
        $tyreHistory= $tyreHistory->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->get();
        return response()->json([
            'success' => true,
            'message' => 'Tyre inspection history list retrieved successfully',
            'total' => $count,
            'data' => $tyreHistory
        ], 200);
        
    }
}
