<?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\Rims\Rims;
use App\Models\Rims\RimHistory;
use App\Models\Rims\RimServiceHistory;
use App\Models\Rims\RimInspectionHistory;
 
use App\Models\Vehicles\Vehicles;
use App\Models\Vehicles\VehicleRims;

use App\Models\Trailers\Trailers;
use App\Models\Trailers\TrailerRims;

use App\Models\Masters\RimServiceType;
use App\Models\Masters\RimActionType;

use App\Models\Masters\ActionType;
use App\Models\Masters\RimInspection;

use App\Models\Inventory\RimInventory;
use App\Models\Inventory\InventoryHistory;


use Illuminate\Support\Facades\Redirect;

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


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

    $rim = new Rims();
    $rim->rim_id = $request->input('rim_id');
    $rim->brand = $inventory->brand_name;
    $rim->model = $inventory->model;
    $rim->size = $inventory->diameter;
    $rim->bolt_pattern = $inventory->bolt_pattern;
    $rim->offset = $inventory->wheel_offset;
    $rim->material = $inventory->material;
    $rim->color_finish = $inventory->finish;
    $rim->center_bore = $inventory->center_bore;
    $rim->spoke_design = $inventory->spoke_design;
    $rim->purchase_date = $inventory->date;
    $rim->purchase_price = $inventory->unit_price;
    $rim->installation_date = $inventory->installation_date;
    $rim->vehicle_id = $inventory->vehicle_id;
    $rim->current_tire = $inventory->current_tire;
    $rim->mileage_at_installation = $inventory->mileage_at_installation;
    $rim->warranty_type = $inventory->warranty_type;
    $rim->warranty_start_date = $inventory->warranty_start_date;
    $rim->warranty_end_date = $inventory->warranty_end_date;
    $rim->notes_comments = $inventory->remarks;
    $rim->status = $inventory->status;
    $rim->preferred_vehicles = $inventory->preferred_vehicles;
    // Save the rim record
    $rim->save();
    
    $date = date('Y-m-d');
    
    $inventoryHistory = new InventoryHistory;
    $inventoryHistory->date = $date;
    $inventoryHistory->type = 'rim';
    $inventoryHistory->inventory_id = $request->input('item_id');
    $inventoryHistory->item_code = $request->input('rim_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 = 'Rim';
        $UserHistory->action_type = 'Rim Imported from Inventory (' . $item_id . ')';
        $UserHistory->item_id = $rim->id;
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();

    


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

    
   

    public function show($id)
    {
        $tire = Rims::find($id);
        $tire_id= $tire->rim_id;

        
        $service_type = RimServiceType::all();
        $action_type = ActionType::all();
        $faq = RimInspection::all();
        
        $vehicle_tire = VehicleRims::where('rim_id', $tire_id)->first();
        if($vehicle_tire){
          $position=$vehicle_tire->rim_position;
        }
        else{
          $position='';
            
        }
        
        $rim_history = RimHistory::where('rim_id', $id)->take(2)->get();
        $service_history = RimServiceHistory::where('rim_id', $id)->take(2)->get();
        $inspection_history = RimInspectionHistory::where('rim_id', $id)->take(2)->get();
        $inspection = RimInspectionHistory::where('rim_id', $id)
                             ->latest('created_at') 
                             ->first();      
        if($inspection){
            $action_needed= $inspection->action_type;
        }
        else{
          $action_needed='';
            
        }

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

        //dd($emp);
        return view('rim.view', compact('tire','service_type', 'action_type', 'faq'));
    }


    public function edit($id, Request $request)
    {
        $rim = Rims::find($id);

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


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

        return Redirect::back();
    }

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

        return Redirect::back();
    }
    
    public function store_history(Request $request)
    {
        $tire_id = $request->input("rim_id");
        
        $tyre= Rims::find($tire_id);
        $location= $tyre->location_status;
        if($location=='Vehicle'){
           $v_tyre= VehicleRims::where('rim_id', $tyre->rim_id)->first();
           $vid= $v_tyre->vehicle_id;
           $v_tyre->delete();
           
           $vehicle=Vehicles::find($vid);
           $vehicle_id= $vehicle->vehicle_id;
        }
        elseif($location=='Trailer'){
            $v_tyre= TrailerRims::where('rim_id', $tyre->rim_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 RimHistory;
        $type->rim_id = $request->input("rim_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();
        
        session()->flash('success', 'Rim moved successfully.');
        return Redirect::back();
    }

    public function store_service(Request $request)
    {

        $type = new RimServiceHistory;
        $type->rim_id = $request->input("rim_id");
        $type->service_date = $request->input("service_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 = 'Rim';
        $UserHistory->action_type = 'Service added';
        $UserHistory->item_id = $request->input('rim_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->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 = 'Rim';
        $UserHistory->action_type = 'Rim moved to (' . $moved_to . ')';
        $UserHistory->item_id = $request->input('rim_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();
        
        session()->flash('success', 'Rim  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 RimInspectionHistory;
        $type->inspection_user = $user->id;
        $type->rim_id = $request->input("rim_id");
        $type->inspection_date = $request->input("inspection_date");
        $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 = 'Rim';
        $UserHistory->action_type = 'Inspection added';
        $UserHistory->item_id = $request->input('rim_id');
        $UserHistory->date = $date;
        $UserHistory->time = $time;
        $UserHistory->save();


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

    public function rim_activity()
    {
        $activity = UserHistory::where('module', 'Rim')->get();
        $users = User::all();
        return view('rim.activity', compact('activity', 'users'));
    }
    
    
    public function rim_history($id)
    {
         $rim_history = RimHistory::where('rim_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('rim.history', compact('rim_history', 'id', 'action_type','service_type'));
    }
    
    public function service_history($id)
    {
         $service_history = RimServiceHistory::where('rim_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('rim.service_history', compact('service_history', 'id', 'action_type','service_type'));
    }
    
    public function inspection_history($id)
    {
        $inspection_history = RimInspectionHistory::where('rim_id', $id)->get();
        $service_type = ServiceType::all();
        $action_type = ActionType::all();
       
        return view('rim.inspection_history', compact('inspection_history', 'id', 'action_type','service_type'));
    }
    
    public function rim_position($id, $id1)
    {

        $tire = Rims::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('rim.rim_position', compact('id','data',  'position', 'vehicle'));
    }
    
    
}
