<?php

namespace App\Http\Controllers\Admin\File;

use Illuminate\Support\Facades\Auth;
use App\Models\User\UserHistory;
use App\Models\User;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Battery\Batteries;
use App\Models\Masters\BatteryServiceType;
use App\Models\Masters\ActionType;
use App\Models\Masters\BatteryInspection;

use App\Models\Battery\BatteryHistory;
use App\Models\Battery\BatteryServiceHistory;
use App\Models\Battery\BatteryInspectionHistory;

use App\Models\Vehicles\Vehicles;
use App\Models\Vehicles\VehicleBatteries;

use App\Models\Trailers\Trailers;
use App\Models\Trailers\TrailerBatteries;

use App\Models\Inventory\BatteryInventory;
use App\Models\Inventory\InventoryHistory;
use Illuminate\Support\Facades\Redirect;

class BatteryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(Request $request)
    {
        $batteries = Batteries::orderBy('id', 'DESC')->get();
        return view('battery.index', compact('batteries'));
    }


    public function create()
    {
         $tyres = BatteryInventory::all();
        return view('battery.create', compact('tyres'));
    }
    
    
    
    public function store(Request $request)
{
    
    $tire_id = $request->input('item_id');
    $inventory = BatteryInventory::find($tire_id);

    // Create a new tyre instance and populate it with request data
    $battery = new Batteries;

    // Assign all request fields to the corresponding model fields
    $battery->battery_id = $request->input('battery_id');
    // Assuming you have $inventory and $tire objects
   // Set all the fields from the inventory model to the battery model
$battery->brand = $inventory->brand;
$battery->model = $inventory->model_number;
$battery->voltage = $inventory->voltage;
$battery->dry_weight = $inventory->dry_weight;
$battery->cca = $inventory->cold_cranking_amps;
$battery->reserve_capacity = $inventory->reserve_capacity_minutes;
$battery->purchase_date = $inventory->date;
$battery->purchase_cost = $inventory->unit_price;
$battery->installation_date = $inventory->installation_date;
$battery->vehicle_id = $inventory->vehicle_id;
$battery->current_vehicle = $inventory->current_vehicle;
$battery->mileage_at_installation = $inventory->mileage_at_installation;
$battery->warranty_type = $inventory->warranty_type;
$battery->warranty_start_date = $inventory->warranty_start_date;
$battery->warranty_end_date = $inventory->warranty_end_date;
$battery->notes_comments = $inventory->remarks;
$battery->status = $inventory->status;
$battery->preferred_vehicles = $inventory->preferred_vehicles;

    // Save the tire to the database
    $battery->save();
    
    $date = date('Y-m-d');
    
    $inventoryHistory = new InventoryHistory;
    $inventoryHistory->date = $date;
    $inventoryHistory->type = 'battery';
    $inventoryHistory->inventory_id = $request->input('item_id');
    $inventoryHistory->item_code = $request->input('battery_id');
    $inventoryHistory->save();

    $item_id = $request->input("item_id");
        $date = date('Y-m-d');
        $time = date('H:i:s');  
        $user = Auth::user();
        $UserHistory = new UserHistory();
        $UserHistory->user_id = $user->id;
        $UserHistory->module = 'Battery';
        $UserHistory->action_type = 'Battery Imported from Inventory (' . $item_id . ')';
        $UserHistory->item_id = $battery->id;
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();

    


    // Redirect to the tyre's details page or the index page
    session()->flash('success', 'Battery Added Successfully');
    return redirect()->route('battery');
}

    
   

    public function show($id)
    {
        $tire = Batteries::find($id);
        $service_type = BatteryServiceType::all();

        $tire = Batteries::find($id);
        $tire_id= $tire->battery_id;

        
        $service_type = BatteryServiceType::all();
        $action_type = ActionType::all();
        $faq = BatteryInspection::all();
        
        $vehicle_tire = VehicleBatteries::where('battery_id', $tire_id)->first();
        if($vehicle_tire){
          $position=$vehicle_tire->battery_position;
        }
        else{
          $position='';
            
        }
        
        $battery_history = BatteryHistory::where('battery_id', $tire_id)->take(2)->get();
        $service_history = BatteryServiceHistory::where('battery_id', $id)->take(2)->get();
        $inspection_history = BatteryInspectionHistory::where('battery_id', $id)->take(2)->get();
        $inspection = BatteryInspectionHistory::where('battery_id', $id)
                             ->latest('created_at') 
                             ->first();      
        if($inspection){
            $action_needed= $inspection->action_type;
        }
        else{
          $action_needed='';
            
        }

     
        return view('battery.view', compact('tire', 'faq', 'action_type', 'service_type', 'battery_history', 'service_history', 'inspection_history', 'position', 'action_needed'));
            

        return view('battery.view', compact('tire','service_type'));
    }


    public function edit($id, Request $request)
    {
        $battery = Batteries::find($id);

        return view('battery.edit', compact('battery'));
    }


    public function update($id, Request $request)
    {
        $tyre = Batteries::find($id);
       
        $tyre->status = $request->input("status") ? "Active" : "Inactive";
        $tyre->save();
        session()->flash('success', 'Tyre Updated Successfully');

        return Redirect::back();
    }

    public function destroy($id)
    {
        $tyre = Batteries::find($id);
        $tyre->delete();
        session()->flash('success', 'Tyre Deleted Successfully');

        return Redirect::back();
    }
    
    
    public function store_history(Request $request)
    {
        $tire_id = $request->input("battery_id");
        
        $tyre= Batteries::find($tire_id);
        $location= $tyre->location_status;
        if($location=='Vehicle'){
           $v_tyre= VehicleBatteries::where('battery_id', $tyre->battery_id)->first();
           $vid= $v_tyre->vehicle_id;
           $v_tyre->delete();
           
           $vehicle=Vehicles::find($vid);
           $vehicle_id= $vehicle->vehicle_id;
        }
        elseif($location=='Trailer'){
            $v_tyre= TrailerBatteries::where('battery_id', $tyre->battery_id)->first();
            $vid= $v_tyre->trailer_id;
            $v_tyre->delete();
            
            $vehicle=Trailers::find($vid);
            $vehicle_id= $vehicle->trailer_id;
         }
        else{
            $vehicle_id='';

        }
        
        $tyre->location_status= $request->input("moved_to");
        $tyre->save();
        
        $type = new BatteryHistory;
        $type->battery_id = $request->input("battery_id");
        $type->date = $request->input("date");
        $type->moved_from = $location;
        $type->moved_to = $request->input("moved_to");
        $type->vehicle_id= $vehicle_id;
        $type->attachment = $request->input("attachment");
        $type->remark = $request->input("remark");
        $type->save();

        $moved_to = $request->input("moved_to");
        $date = date('Y-m-d');
        $time = date('H:i:s');  
        $user = Auth::user();
        $UserHistory = new UserHistory();
        $UserHistory->user_id = $user->id;
        $UserHistory->module = 'Battery';
        $UserHistory->action_type = 'Battery moved to (' . $moved_to . ')';
        $UserHistory->item_id = $request->input('battery_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();
        
        session()->flash('success', 'Battery moved successfully.');
        return Redirect::back();
    }

    public function store_service(Request $request)
    {

        $type = new BatteryServiceHistory;
        $type->battery_id = $request->input("battery_id");
        $type->service_date = $request->input("service_date");
        $type->service_type = $request->input("service_type");
        $type->cost = $request->input("cost");
        $type->attachment = $request->input("attachment");
        $type->description = $request->input("description");
       
        $type->save();

        $date = date('Y-m-d');
        $time = date('H:i:s');  
        $user = Auth::user();
        $UserHistory = new UserHistory();
        $UserHistory->user_id = $user->id;
        $UserHistory->module = 'Tyre';
        $UserHistory->action_type = 'Service added';
        $UserHistory->item_id = $request->input('battery_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();
        
        session()->flash('success', 'Battery  Service added successfully.');
        return Redirect::back();
    }


    public function store_inspection(Request $request)
    {
        
    $faqQuestions = $request->input('faq_question');
    $faqAnswers = $request->input('faq_answer');

    $faqData = [];

    // Assuming the questions and answers are of the same count
    $count = count($faqQuestions);

    for ($i = 0; $i < $count; $i++) {
        $faqData[] = [
            'question' => $faqQuestions[$i],
            'answer' => $faqAnswers[$i],
        ];
    }

    // Convert the FAQ data to JSON
    $faqJson = json_encode($faqData);

        $user = Auth::user();

        // dd($request);
        $type = new BatteryInspectionHistory;
        $type->inspection_user = $user->id;
        $type->battery_id = $request->input("battery_id");
        $type->inspection_date = $request->input("inspection_date");
        $type->cca = $request->input("cca");
        $type->reserve_capacity = $request->input("reserve_capacity");
        $type->faq = $faqJson;
        $type->action_type = $request->input("action_type");
        $type->description = $request->input("description"); 
        
        if ($request->file('attachment')) {
            $photo = $request->file('attachment');
            $filename = time() . '.' . $photo->getClientOriginalExtension();
            $path = public_path('uploads');
            $photo->move($path, $filename);
            $type->attachment = $filename;
        }
        
        $type->save();

        $date = date('Y-m-d');
        $time = date('H:i:s');  
        $user = Auth::user();
        $UserHistory = new UserHistory();
        $UserHistory->user_id = $user->id;
        $UserHistory->module = 'Battery';
        $UserHistory->action_type = 'Inspection added';
        $UserHistory->item_id = $request->input('battery_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();


        session()->flash('success', 'Battery  Inspection added successfully.');
        return Redirect::back();
    }

    public function battery_activity()
    {
        $activity = UserHistory::where('module', 'Battery')->get();
        $users = User::all();
        return view('battery.activity', compact('activity', 'users'));
    }

    public function battery_history($id)
    {
        $battery_history = batteryHistory::where('battery_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('battery.history', compact('battery_history', 'id', 'action_type','service_type'));
    }
    
    
     public function service_history($id)
    {
        $service_history = BatteryServiceHistory::where('battery_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('battery.service_history', compact('service_history', 'id', 'action_type','service_type'));
    }
    
    public function inspection_history($id)
    {
        $inspection_history = BatteryInspectionHistory::where('battery_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('battery.inspection_history', compact('inspection_history', 'id', 'action_type','service_type'));
    }
    
}
