<?php

namespace App\Http\Controllers\Api\Tms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tms\RimStock;
use App\Models\Tms\RimDetail;
use App\Models\Tms\RimHistory;
use App\Models\Tms\RimServiceHistory;
use App\Models\Tms\RimInspectionHistory;
use App\Models\Tms\Vehicles\VehicleInstallation;
use App\Models\Tms\Trailers\TrailerInstallation;
use App\Models\Item;
use Validator;
use Auth;
use Carbon\Carbon;

class RimController extends Controller
{
    public function rimList(Request $request)
    {
        $rim_detail = RimDetail::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') != '') {
            $rim_detail->where('brand', 'like', '%' . $request->input('brand') . '%');
        }
        if ($request->has('model') && $request->input('model') != '') {
            $rim_detail->where('model', 'like', '%' . $request->input('model') . '%');
        }
    
        if ($request->has('location_status') && $request->input('location_status') != '') {
            $rim_detail->where('location_status', 'like', '%' . $request->input('location_status') . '%');
        }

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

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

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

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

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

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

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

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

    // Creating a new rim stock
    public function rimStockCreate(Request $request)
    {

        // Validate 
        $validator=validator($request->all(),[
            'rim_id'=>'required',
            'rim_detail_id'=>'required',
            'item_id'=>'required',
        ]);

        if ($validator->fails()) {

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

        } else {

            // Check if the Rim Id already exists
            $existingRimStock = RimStock::where('rim_id', $request['rim_id'])->first();
            if ($existingRimStock) {
                return response()->json([
                    'message' => 'Rim With ID already exists',
                    'success' => false,
                    'data' => $existingRimStock
                ], 200);
            }

             // 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['rim_id'] = $request['rim_id'];
            $obj['rim_detail_id'] = $request['rim_detail_id']??0; // required – no default
            $obj['item_id'] = $request['item_id']; // required – no default
            $obj['brand'] = $request['brand'];
            $obj['model'] = $request['model'];
            $obj['size'] = $request['size'];
            $obj['bolt_pattern'] = $request['bolt_pattern'];
            $obj['offset'] = $request['offset'];
            $obj['material'] = $request['material'];
            $obj['color_finish'] = $request['color_finish'];
            $obj['center_bore'] = $request['center_bore'];
            $obj['spoke_design'] = $request['spoke_design'];
            $obj['purchase_date'] = $request['purchase_date'];
            $obj['purchase_price'] = $request['purchase_price'];
            $obj['rim_condition'] = $request['rim_condition'];
            $obj['warranty_type'] = $request['warranty_type'];

            $obj['notes_comments'] = $request['notes_comments'];
            $obj['status'] = $request['status'] ?? 'Active';
            $obj['location_status'] = $request['location_status'] ?? 'Store';
            $obj['preferred_vehicles'] = $request['preferred_vehicles'] ?? '';

            $rimStock = RimStock::create($obj);

            $rimStock['description']="Rim Stock with Rim id: ".$rimStock['rim_id']." moved to TMS store";

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

            //Creating History
            $obj1['rim_id'] = $rimStock['id']; // required – no default  //From the RIm Stock lIst
            $obj1['date'] = Carbon::now()->toDate('Y-m-d');
            $obj1['moved_to'] = 'Tms Store';
            $obj1['moved_from'] = 'Store'; // From the Rim Stock List
            $obj1['vehicle_id'] = $request['vehicle_id'] ?? 0;
            $obj1['remark'] = 'Rim Stock with Rim id: '.$request['rim_id'].' moved to TMS store';
            $obj1['attachment'] = $request['attachment'] ?? null;

            $rimHistory = RimHistory::create($obj1);

            return response()->json([
                'message' => 'Rim stock created successfully',
                'success' => true,
                'data' => $rimStock
            ], 200);
        }
    }

    // Getting Stock Lists of Batteries
    public function rim_stock_list(Request $request)
    {
        $rimStock = RimStock::query();

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

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

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

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

        $count = $rimStock->count();

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

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

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

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

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

    //Rim Stock Details
    public function rim_stock_details(Request $request){

         $validator = Validator::make($request->all(), [
            'rim_id' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null
            ], 200);
        }
        $rimStock = RimStock::where('id', $request['rim_id'])
            ->with('rim_details','trailer','trailer.trailer_installations','vehicle','vehicle.vehicle_installations','vehicle.trailer')
            ->first();

        $rim_inspection_history = RimInspectionHistory::where('rim_id', $request['rim_id'])
            ->orderBy('id', 'desc')
            ->first();
            
        if (!$rimStock) {
            return response()->json([
                'message' => 'Rim not found',
                'success' => false,
                'data' => null
            ], 404);
        }
        return response()->json([
            'message' => 'Rim stock details retrieved successfully',
            'success' => true,
            'data' => $rimStock,
            'rim_inspection_history' => $rim_inspection_history
        ], 200);
    }

    // Rim Move History Create
    public function rimHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'rim_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 rim exists
            $rimStock = RimStock::where('id', $request['rim_id'])->first();

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

            if($rimStock->vehicle_id > 0){

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

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

            }

            if($rimStock->trailer_id > 0){ 

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

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

            }

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

            $rimHistory = RimHistory::create($obj);

            // Update the rim stock location status
            $rimStock->location_status = $request['moved_to'];
            $rimStock->update();

            return response()->json([
                'message' => 'Rim moved successfully',
                'success' => true,
                'data' => $rimHistory
            ], 200);
        }
    }

    // Rim Move History List
    public function rimHistoryList(Request $request)
    {
        $rimHistory = RimHistory::query();

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

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

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

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

    // Rim Service History Create
    public function rimServiceHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'rim_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 rim exists
            $rimStock = RimStock::where('id', $request['rim_id'])->first();
            if (!$rimStock) {
                return response()->json([
                    'message' => 'Rim not found',
                    'success' => false,
                    'data' => null
                ], 200);
            }

            $obj['rim_id'] = $request['rim_id']; // required – no default  //From the Rim 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;

            $rimHistory = RimServiceHistory::create($obj);

            return response()->json([
                'message' => 'Rim service history created successfully',
                'success' => true,
                'data' => $rimHistory
            ], 201);
        }
    }

    // Rim Service History List
    public function rimServiceHistoryList(Request $request)
    {
        $rimHistory = RimServiceHistory::query();

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

        $count = $rimHistory->count();

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

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

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

    // Rim Inspection History Create
    public function rimInspectionHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'rim_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 rim exists
            $rimStock = RimStock::where('id', $request['rim_id'])->first();
            if (!$rimStock) {
                return response()->json([
                    'message' => 'Rim not found In the Stock List',
                    'success' => false,
                    'data' => null
                ], 200);
            }

            $obj['rim_id'] = $request['rim_id']; // required – no default  //From the Rim Stock lIst
            $obj['inspection_date'] = $request['inspection_date']??null; // required – no default
            $obj['inspection_user'] = $request['inspection_user'] ?? 0;
            $obj['faq'] = $request['faq'] ?? null;
            $obj['rim_condition'] = $request['rim_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;

            $rimHistory = RimInspectionHistory::create($obj);

            return response()->json([
                'message' => 'Rim inspection history created successfully',
                'success' => true,
                'data' => $rimHistory
            ], 201);
        }
    }

    // Rim Inspection History List
    public function rimInspectionHistoryList(Request $request)
    {
        $rimHistory = RimInspectionHistory::query();

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

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

        $count = $rimHistory->count();

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

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