<?php

namespace App\Http\Controllers\Api\Tms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tms\BatteryStock;
use App\Models\Tms\BatteryDetail;
use App\Models\Tms\BatteryHistory;
use App\Models\Tms\BatteryServiceHistory;
use App\Models\Tms\BatteryInspectionHistory;
use App\Models\Tms\Vehicles\VehicleInstallation;
use App\Models\Tms\Trailers\TrailerInstallation;
use App\Models\Item;
use Validator;
use Auth;
use Carbon\Carbon;

class BatteryController extends Controller
{

    // Battery Item Details List
    public function batteryList(Request $request)
    {
        $batteryDetail = BatteryDetail::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') != '') {
            $batteryDetail->where('brand', 'like', '%' . $request->input('brand') . '%');
        }
        if ($request->has('model') && $request->input('model') != '') {
            $batteryDetail->where('model', 'like', '%' . $request->input('model') . '%');
        }
        if ($request->has('location_status') && $request->input('location_status') != '') {
            $batteryDetail->where('location_status', 'like', '%' . $request->input('location_status') . '%');
        }

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

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

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

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

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

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

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

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

    // Creating a new battery stock
    public function batteryStockCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'battery_id'=>'required',
            'item_id'=>'required',
            'battery_detail_id'=>'required',
        ]);

        if ($validator->fails()) {

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

        } else {

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

            // Check if the Battery 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['battery_id'] = $request['battery_id']; // required – no default
            $obj['battery_detail_id'] = $request['battery_detail_id']; // required – no default
            $obj['item_id'] = $request['item_id']; // required – no default
            $obj['brand'] = $request['brand'] ?? null;
            $obj['model'] = $request['model'] ?? null;
            $obj['voltage'] = $request['voltage'] ?? 0.0;
            $obj['dry_weight'] = $request['dry_weight'] ?? null;
            $obj['cca'] = $request['cca'] ?? 0;
            $obj['reserve_capacity'] = $request['reserve_capacity'] ?? 0;
            $obj['purchase_date'] = $request['purchase_date'] ??null;
            $obj['purchase_cost'] = $request['purchase_cost'] ?? 0.00;
            $obj['installation_date'] = $request['installation_date'] ?? null;
            // $obj['vehicle_id'] = $request['vehicle_id'] ?? 0;
            // $obj['current_vehicle'] = $request['current_vehicle'] ?? null;
            $obj['mileage_at_installation'] = $request['mileage_at_installation'] ?? 0;
            $obj['battery_condition'] = $request['battery_condition'] ?? 'Good';
            $obj['warranty_type'] = $request['warranty_type'] ?? null;
            $obj['warranty_start_date'] = $request['warranty_start_date'] ?? null;
            $obj['warranty_end_date'] = $request['warranty_end_date'] ?? null;
            $obj['notes_comments'] = $request['notes_comments'] ?? null;
            $obj['status'] = $request['status'] ?? 'Active';
            $obj['location_status'] = $request['location_status'] ?? 'Store';
            $obj['preferred_vehicles'] = $request['preferred_vehicles'] ?? '';

            $batteryStock = BatteryStock::create($obj);

            $batteryStock['description']="Battery Stock with Battery id: ".$batteryStock['battery_id']." moved to TMS store";
            
             // Update TMS Store
            $itemStock->tms_store = $itemStock->tms_store - 1;
            $itemStock->update();

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

            $batteryHistory = BatteryHistory::create($obj1);

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

    // Getting Stock Lists of Batteries
    public function batteryStockList(Request $request)
    {
        $batteryStock = BatteryStock::query();

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

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

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

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

        $count = $batteryStock->count();

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

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

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

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

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

    // Battery Stock Details
    public function batteryStockDetails(Request $request){
         // Validate the request
        $validator = Validator::make($request->all(), [
            'battery_id' => 'required',
        ]);

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

        // Find the battery stock by ID
        $batteryStock = BatteryStock::where('id', $request['battery_id'])
            ->with('battery_details','vehicle','vehicle.vehicle_installations','vehicle.trailer','trailer','trailer.trailer_installations') // Eager load the battery detail relationship
            ->first();

        $battery_inspection_history = BatteryInspectionHistory::where('battery_id', $request['battery_id'])
            ->orderBy('inspection_date', 'desc')
            ->first();
            
        if (!$batteryStock) {
            return response()->json([
                'success' => false,
                'message' => 'Battery not found',
                'data' => null
            ], 200);
        }

        return response()->json([
            'success' => true,
            'message' => 'Battery stock details retrieved successfully',
            'data' => $batteryStock,
            'battery_inspection_history' => $battery_inspection_history
        ], 200);


    }

    // Battery Move History Create
    public function batteryHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'battery_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 battery exists
            $batteryStock = BatteryStock::where('id', $request['battery_id'])->first();
            if (!$batteryStock) {
                return response()->json([
                    'success' => false,
                    'message' => 'Battery not found',
                    'data' => null
                ], 404);
            }

             if($batteryStock->vehicle_id > 0){

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

                $batteryStock['installation_date']=null;
                $batteryStock['vehicle_id']=0;
                // $batteryStock['position_on_vehicle']=null;

            }

            if($batteryStock->trailer_id > 0){ 

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

                $batteryStock['installation_date']=null;
                $batteryStock['trailer_id']=0;
                // $batteryStock['position_on_trailer']=null;

            }

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

            $batteryHistory = BatteryHistory::create($obj);

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

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

    // Battery Move History List
    public function batteryHistoryList(Request $request)
    {
        $batteryHistory = BatteryHistory::query();

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

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

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

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

    // Battery Service History Create
    public function batteryServiceHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'battery_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 battery exists
            $batteryStock = BatteryStock::where('id', $request['battery_id'])->first();
            if (!$batteryStock) {
                return response()->json([
                    'success' => false,
                    'message' => 'Battery not found',
                    'data' => null
                ], 404);
            }

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

            $batteryHistory = BatteryServiceHistory::create($obj);

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

    // Battery Service History List
    public function batteryServiceHistoryList(Request $request)
    {
        $batteryHistory = BatteryServiceHistory::query();

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

        $count = $batteryHistory->count();

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

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

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

    // Battery Inspection History Create
    public function batteryInspectionHistoryCreate(Request $request)
    {
        // Validate 
        $validator=validator($request->all(),[
            'battery_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 battery exists
            $batteryStock = BatteryStock::where('id', $request['battery_id'])->first();
            if (!$batteryStock) {
                return response()->json([
                    'success' => false,
                    'message' => 'Battery not found In the Stock List',
                    'data' => null
                ], 404);
            }

            $obj['battery_id'] = $request['battery_id']; // required – no default  //From the Battery Stock lIst
            $obj['inspection_date'] = $request['inspection_date']??null; // required – no default
            $obj['inspection_user'] = $request['inspection_user'] ?? 0;
            $obj['cca'] = $request['cca'] ?? null;
            $obj['reserve_capacity'] = $request['reserve_capacity'] ?? null;
            $obj['faq'] = $request['faq'] ?? null;
            $obj['battery_condition'] = $request['battery_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;

            $batteryHistory = BatteryInspectionHistory::create($obj);

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

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

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

        $count = $batteryHistory->count();

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

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