<?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\Masters\InspectionFaq;
use App\Models\Masters\ActionType;
use App\Models\Masters\ServiceType;

use App\Models\Vehicles\Vehicles;
use App\Models\Vehicles\VehicleTyres;

use App\Models\Trailers\Trailers;
use App\Models\Trailers\TrailerTyres;

use App\Models\Tires\TireServiceHistory;

use App\Models\Tires\TireInspectionHistory;
use App\Models\Tires\Tires;
use App\Models\Tires\TireHistory;
use App\Models\Tires\TyreInspectionHistory;
use App\Models\Inventory\TyreInventory;
use App\Models\Inventory\InventoryHistory;
use Illuminate\Support\Facades\Redirect;

class TyreController 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)
    {
        $tyre = Tires::orderBy('id', 'DESC')->get();
        return view('tyre.index', compact('tyre'));
    }


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

    // Create a new tyre instance and populate it with request data
    $tire = new Tires;

    // Assign all request fields to the corresponding model fields
    $tire->tire_id = $request->input('tire_id');
    // Assuming you have $inventory and $tire objects
    $tire->warranty_type = $inventory->warranty_type;
    $tire->warranty_start_date = $inventory->warranty_start_date;
    $tire->warranty_end_date = $inventory->warranty_end_date;
    $tire->commercial_name = $inventory->commercial_name;
    $tire->brand = $inventory->brand_name;
    $tire->model = $inventory->model;

    $tire->inflation_pressure = $inventory->pressure;
    $tire->tread_depth = $inventory->tread_depth;
    $tire->max_tread_depth = $inventory->maximum_tread_depth;
    $tire->rolling_km = $inventory->rolling_km;
    $tire->max_rolling_km = $inventory->maximum_rolling_km;

    $tire->size = $inventory->rim_diameter_inches;
    $tire->identity = $inventory->identity;
    $tire->purchase_date = $inventory->date;
    $tire->purchase_cost = $inventory->unit_price;
    $tire->load_pressure_information = $inventory->load_pressure_information;
    $tire->indicated_exterior = $inventory->indicated_exterior;
    $tire->type_of_construction = $inventory->type_of_construction;
    $tire->tyre_sections_width_mm = $inventory->tyre_sections_width_mm;
    $tire->section_height_to_section_width_ratio = $inventory->section_height_to_section_width_ratio;
    $tire->rim_diameter_inches = $inventory->rim_diameter_inches;
    $tire->load_capacity_index = $inventory->load_capacity_index;
    $tire->speed_rating = $inventory->speed_rating;
    $tire->load_rating = $inventory->load_rating;
    $tire->tyre_type = $inventory->tyre_type;
    $tire->remarks = $inventory->remarks;
    $tire->preferred_vehicles = $inventory->preferred_vehicles;

    // Save the tire to the database
    $tire->save();
    
    $date = date('Y-m-d');
    
    $inventoryHistory = new InventoryHistory;
    $inventoryHistory->date = $date;
    $inventoryHistory->type = 'tire';
    $inventoryHistory->inventory_id = $request->input('item_id');
    $inventoryHistory->item_code = $request->input('tire_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 = 'Tyre';
        $UserHistory->action_type = 'Tyre Imported from Inventory (' . $item_id . ')';
        $UserHistory->item_id = $tire->id;
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();

    


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


    public function store_history(Request $request)
    {
        $tire_id = $request->input("tire_id");
        
        $tyre= Tires::find($tire_id);
        $location= $tyre->location_status;
        if($location=='Vehicle'){
           $v_tyre= VehicleTyres::where('tyre_id', $tyre->tire_id)->first();
           $vid= $v_tyre->vehicle_id;
           $v_tyre->delete();
           
           $vehicle=Vehicles::find($vid);
           $vehicle_id= $vehicle->vehicle_id;
        }
        elseif($location=='Trailer'){
            $v_tyre= TrailerTyres::where('tyre_id', $tyre->tire_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 TireHistory;
        $type->tire_id = $request->input("tire_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 = 'Tyre';
        $UserHistory->action_type = 'Tyre moved to (' . $moved_to . ')';
        $UserHistory->item_id = $request->input('tire_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();
        
        session()->flash('success', 'Tyre moved successfully.');
        return Redirect::back();
    }
    
    public function store_service(Request $request)
    {

        $type = new TireServiceHistory;
        $type->tire_id = $request->input("tire_id");
        $type->service_date = $request->input("date");
        $type->service_type = $request->input("service_type");
        $type->cost = $request->input("cost");
        $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 = 'Tyre';
        $UserHistory->action_type = 'Service added';
        $UserHistory->item_id = $request->input('tire_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();
        
        session()->flash('success', 'Tyre  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 TireInspectionHistory;
        $type->inspection_user = $user->id;
        $type->tire_id = $request->input("tire_id");
        $type->inspection_date = $request->input("inspection_date");
        $type->tread_depth_mm = $request->input("tread_depth_mm");
        $type->pressure = $request->input("pressure");
        $type->tire_condition = $request->input("tire_condition");
        $type->current_rolling_km = $request->input("current_rolling_km");
        $type->pressure = $request->input("pressure");        $type->pressure = $request->input("pressure");        $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();
        
        $tire_id = $request->input("tire_id");
        $tyre = Tires::find($tire_id);
        $tyre->tread_depth = $request->input("tread_depth_mm");
        $tyre->inflation_pressure = $request->input("pressure");
        $tyre->rolling_km = $request->input("current_rolling_km");
        $tyre->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 = 'Inspection added';
        $UserHistory->item_id = $request->input('tire_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();


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

    
   

    public function show($id)
    {
        $tire = Tires::find($id);
        $tire_id= $tire->tire_id;
        $faq = InspectionFaq::all();
        $action_type = ActionType::all();
        $service_type = ServiceType::all();
        $vehicle_tire = VehicleTyres::where('tyre_id', $tire_id)->first();
        if($vehicle_tire){
          $position=$vehicle_tire->tyre_position;
        }
        else{
          $position='';
            
        }
        
        $tire_history = TireHistory::orderBy('id', 'DESC')->where('tire_id', $id)->take(2)->get();
        $service_history = TireServiceHistory::orderBy('id', 'DESC')->where('tire_id', $id)->take(2)->get();
        $inspection_history = TireInspectionHistory::orderBy('id', 'DESC')->where('tire_id', $id)->take(2)->get();
        $inspection = TireInspectionHistory::where('tire_id', $id)
                             ->latest('created_at') 
                             ->first();      
       if($inspection){
            $action_needed= $inspection->action_type;
        }
        else{
          $action_needed='';
            
        }

     
        return view('tyre.view', compact('tire', 'faq', 'action_type', 'service_type', 'tire_history', 'service_history', 'inspection_history', 'position', 'action_needed'));
    }
    
    public function tyre_activity()
    {
        $activity = UserHistory::where('module', 'Tyre')->get();
        $users = User::all();
        return view('tyre.activity', compact('activity', 'users'));
    }


    public function tyre_history($id)
    {
        $tyre_history = TireHistory::where('tire_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('tyre.history', compact('tyre_history', 'id', 'action_type','service_type'));
    }
    
    public function service_history($id)
    {
         $service_history = TireServiceHistory::where('tire_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('tyre.service_history', compact('service_history', 'id', 'action_type','service_type'));
    }
    
    public function inspection_history($id)
    {
        $inspection_history = TireInspectionHistory::where('tire_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('tyre.inspection_history', compact('inspection_history', 'id', 'action_type','service_type'));
    }
    
    public function tyre_position($id, $id1)
    {

        $tire = Tires::find($id);
        $vehicle_id= $tire->vehicle_id;
        $position= $tire->position_on_vehicle;

        $vehicle = Vehicles::find($vehicle_id);
        $image= $vehicle->axle_tyre_configuration;
        $data = json_decode($image, true);
        
        return view('tyre.tyre_position', compact('id','data',  'position', 'vehicle'));
    }


    public function edit($id, Request $request)
    {
        $tire = Tires::find($id);

        return view('tyre.edit', compact('tire'));
    }


    public function update(Request $request)
    {
        $id = $request->input('tire_id');
        $tire = Tires::find($id);
        
    $tire->brand = $request->input('brand');
    $tire->model = $request->input('model');
    $tire->size = $request->input('size');
    $tire->purchase_date = $request->input('purchase_date');
    $tire->purchase_cost = $request->input('purchase_cost');
    $tire->installation_date = $request->input('installation_date');
    $tire->vehicle_id = $request->input('vehicle_id');
    $tire->position_on_vehicle = $request->input('position_on_vehicle');
    $tire->temperature = $request->input('temperature');
    $tire->load_rating = $request->input('load_rating');
    $tire->speed_rating = $request->input('speed_rating');
    $tire->dot_number = $request->input('dot_number');
    $tire->status = $request->input('status');
    // $tire->warranty_provider = $request->input('warranty_provider');
    $tire->warranty_type = $request->input('warranty_type');
    $tire->warranty_start_date = $request->input('warranty_start_date');
    $tire->warranty_end_date = $request->input('warranty_end_date');
    $tire->notes_comments = $request->input('notes_comments');
    $tire->barcode_qr_code = $request->input('barcode_qr_code');
    $tire->commercial_name = $request->input('commercial_name');
    $tire->identity = $request->input('identity');
    $tire->load_pressure_information = $request->input('load_pressure_information');
    $tire->indicated_exterior = $request->input('indicated_exterior');
    $tire->type_of_construction = $request->input('type_of_construction');
    $tire->tyre_sections_width_mm = $request->input('tyre_sections_width_mm');
    $tire->section_height_to_section_width_ratio = $request->input('section_height_to_section_width_ratio');
    $tire->rim_diameter_inches = $request->input('rim_diameter_inches');
    $tire->load_capacity_index = $request->input('load_capacity_index');
    $tire->tyre_type = $request->input('tyre_type');
    $tire->remarks = $request->input('remarks');
       
        // $tire->status = $request->input("status") ? "Active" : "Inactive";
        $tire->save();
        session()->flash('success', 'Tyre Updated Successfully');

        return Redirect::back();
    }

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

        return Redirect::back();
    }
}
