<?php

namespace App\Http\Controllers;

use App\Models\Brand;
use App\Models\Devis;
use App\Models\Dossier;
use App\Models\Operation;
use App\Models\Piece;
use App\Models\PieceMode;
use App\Models\PieceType;
use App\Models\Rapport;
use App\Models\RapportPiece;
use App\Models\TypeReparation;
use App\Models\VehiculeModel;
use Illuminate\Http\Request;

class PieceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authorize('viewAny', Piece::class);
        $pieces = Piece::with('vehiculemodel', 'vehiculemodel.brand', 'operation')->whereHas('piecetype', function ($query) {
            $query->where('svg',1);
        })->get();

        return view('configuration.Piece.index', compact('pieces'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create', Piece::class);
        $piecetypes = PieceType::where('svg',1)->get();
        return view('configuration.Piece.create', compact('piecetypes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->authorize('create', Piece::class);

        $request->validate([
            'piece' => 'required|unique:pieces,piece',
            'piece_type_id' => 'required',
        ]);


        Piece::create([
            'piece' => $request->piece,
            'piece_type_id' => $request->piece_type_id,
        ]);

        return redirect()->back()->with('success', 'Piece Créer avec Succés');
    }

    public function storefromrapport(Request $request)
    {
        $this->authorize('create', Piece::class);

        $request->validate([
            'piece' => 'required',
            'vehicule_model_id' => 'required',
            'prix_unitaire' => 'required|numeric',
            'type_reparation_id' => 'required',
            'piece_type_id' => 'required',
            'operation' => 'required',
            'qte' => 'required',
        ]);
        $rapport = Rapport::whereId($request->rapport_id)->with('dossier')->firstOrFail();
        $piece = Piece::whereId($request->piece)->first();
        // $piece = Piece::create([
        //     'piece' => $request->piece,
        //     'vehicule_model_id' => $request->vehicule_model_id,
        //     'piece_type_id' => $request->piece_type_id,
        //     'prix_unitaire' => $request->prix_unitaire,
        //     'type_reparation_id' => $request->type_reparation_id,
        //     'operation_id' => $request->operation,
        //     // 'gravite'=>$request->gravite,
        //     // 'etat'=>$request->etat,
        // ]);
        if ($request->type_reparation_id == 1) {
            $montant = $piece->prix_unitaire * $request->qte - ($piece->prix_unitaire * $request->qte * ($request->vetuste / 100)) - ($piece->prix_unitaire * $request->qte * ($request->remise / 100));
        } else {
            if ($rapport->dossier->type_expertise_id != 14) {
                $montant = $piece->prix_unitaire * $request->qte + $piece->prix_unitaire * $request->qte * 0.2 - (($piece->prix_unitaire * $request->qte + $piece->prix_unitaire * $request->qte * 0.2) * ($request->vetuste / 100)) - (($piece->prix_unitaire * $request->qte + $piece->prix_unitaire * $request->qte * 0.2) * ($request->remise / 100));
            } else {
                $montant = $piece->prix_unitaire * $request->qte - ($piece->prix_unitaire * $request->qte * ($request->vetuste / 100));
            }
        }

        $rapport->piece()->attach($piece, [
            'qte' => $request->qte, 'prix_unitaire' => $request->prix_unitaire, 'gravite' => $request->gravite, 'etat' => $request->etat, 'vetuste' => $request->vetuste ?? 0, 'remise' => $request->remise ?? 0, 'montant_ht' => $montant,
            'type_reparation_id' => $request->type_reparation_id, 'operation_id' => $request->operation, 'vehicule_model_id' => $rapport->dossier->vehicule_model_id
        ]);

        return redirect()->back()->with('success', 'Piece Créer avec Succés');
    }

    public function storefromdevis(Request $request)
    {
        $this->authorize('create', Piece::class);


        $request->validate([
            'piece' => 'required',
            'prix_unitaire' => 'required|numeric',
            'type_reparation_id' => 'required',
            'operation' => 'required',
            'qte' => 'required',
        ]);

        $devis = Devis::whereId($request->devis_id)->with('dossier')->firstOrFail();
        $piece = Piece::whereId($request->piece)->first();

        if ($request->type_reparation_id == 1) {
            $montant = $piece->prix_unitaire * $request->qte - ($piece->prix_unitaire * $request->qte * ($request->vetuste / 100)) - ($piece->prix_unitaire * $request->qte * ($request->remise / 100));
        } else {
            if ($devis->dossier->type_expertise_id != 14) {
                $montant = $piece->prix_unitaire * $request->qte + $piece->prix_unitaire * $request->qte * 0.2 - (($piece->prix_unitaire * $request->qte + $piece->prix_unitaire * $request->qte * 0.2) * ($request->vetuste / 100)) - (($piece->prix_unitaire * $request->qte + $piece->prix_unitaire * $request->qte * 0.2) * ($request->remise / 100));
            } else {
                $montant = $piece->prix_unitaire * $request->qte - ($piece->prix_unitaire * $request->qte * ($request->vetuste / 100));
            }
        }


        $devis->piece()->attach($piece, [
            'qte' => $request->qte, 'prix_unitaire' => $request->prix_unitaire, 'gravite' => $request->gravite, 'etat' => $request->etat, 'vetuste' => $request->vetuste ?? 0, 'remise' => $request->remise ?? 0, 'montant_ht' => $montant,
            'type_reparation_id' => $request->type_reparation_id, 'operation_id' => $request->operation, 'vehicule_model_id' => $devis->dossier->vehicule_model_id
        ]);

        return redirect()->back()->with('success', 'Piece Créer avec Succés');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Piece  $piece
     * @return \Illuminate\Http\Response
     */
    public function attach(Request $request, $id)
    {
        $devis = Devis::whereId($request->devis_id)->first();
        $piece = Piece::whereId($id)->first();
        // if(empty($request->qte)){
        //     return redirect()->back()->with('error','Svp de remplire la Quantité');
        // }
        // if(empty($request->vetuste)){
        //     return redirect()->back()->with('error','Svp de remplire la Vetuste');
        // }
        // if(empty($request->remise)){
        //     return redirect()->back()->with('error','Svp de remplire la Remise');
        // }
        $montant2 = $piece->prix_unitaire * ($request->vetuste / 100);
        $montant3 = $piece->prix_unitaire * ($request->remise / 100);
        $montant1 = $piece->prix_unitaire - $montant2 - $montant3;
        $montant = $montant1 * $request->qte;
        $devis->piece()->attach($piece, ['qte' => $request->qte, 'prix_unitaire' => $request->prix_unitaire, 'gravite' => $request->gravite, 'etat' => $request->etat, 'vetuste' => $request->vetuste, 'remise' => $request->remise, 'montant_ht' => $montant]);
        return redirect()->back()->with('success', 'Piece Ajouter avec Succés');
    }

    public function remove(Request $request, $id)
    {

        $devis = Devis::whereId($request->devis_id)->first();
        $piece = Piece::whereId($id)->first();
        $devis->piece()->detach($piece->id);
        return redirect()->back()->with('success', 'Piece Ajouter avec Succés');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Piece  $piece
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authorize('update', Piece::class);

        $piece = Piece::whereId($id)->with('vehiculemodel', 'vehiculemodel.brand','piecetype')->first();
        // dd($piece);
        return view('configuration.Piece.edit', compact('piece'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Piece  $piece
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authorize('update', Piece::class);

        $request->validate([
            'piece' => 'required',
        ]);
        $piece = Piece::whereId($id)->first();
        $piece->piece = $request->piece;
        $piece->update();
        return redirect()->route('Piece.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Piece  $piece
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $piece = Piece::whereId($id)->first();
        $piece->delete();
        return redirect()->route('Piece.index');
    }

    public function deleted()
    {
        $pieces = Piece::onlyTrashed()->with('pieceType')->get();
        return view('configuration.piece.deleted', compact('pieces'));
    }

    public function restore($id)
    {
        Piece::withTrashed()->find($id)->restore();
        return redirect()->route('Piece.index');
    }

    public function lastprice(Request $request)
    {

        $price = 0;

        if (!$request->piece_id && !$request->vehicule_id && !$request->type && !$request->operation_id) {
            return response()->json($price);
        }

        // $dossiers = Dossier::where('vehicule_model_id',$request->vehicule_id)
        // ->with('onerapport.piece','onedevis.piece')->latest()->get();

        // foreach ($dossiers as $dossier) {
        //     foreach ($dossier->onedevis->piece as $piece) {
        //         if(($piece->pivot->piece_id == $request->piece_id)&&($piece->pivot->type_reparation_id == $request->type)&&($piece->pivot->operation_id == $request->operation_id)){
        //             $rp = RapportPiece::where('piece_id',$request->piece_id)
        //             ->where('type_reparation_id',$request->type)
        //             ->where('vehicule_model_id',$request->vehicule_id)
        //             ->where('operation_id',$request->operation_id)
        //             ->latest()->first();
        //             $price = $rp->prix_unitaire;
        //             $price = $piece->pivot->prix_unitaire;
        //         }
        //     }
        //     if($price == 0){
        //         foreach ($dossier->onerapport->piece as $piece) {
        //             if(($piece->pivot->piece_id == $request->piece_id)&&($piece->pivot->type_reparation_id == $request->type)&&($piece->pivot->operation_id == $request->operation_id)){
        //                 $price = $piece->pivot->prix_unitaire;
        //             }
        //         }
        //     }
        // }
        $rp = RapportPiece::where('piece_id', $request->piece_id)
            ->where('type_reparation_id', $request->type)
            ->where('vehicule_model_id', $request->vehicule_id)
            ->where('operation_id', $request->operation_id)
            ->latest()->first();
        if ($rp) {
            $price = $rp->prix_unitaire;
        }

        return response()->json($price);
    }
}
