<?php

namespace App\Http\Controllers;

use App\Models\Devis;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\DossierStatus;
use App\Models\Facture;
use App\Models\Meeting;
use App\Models\Montant;
use App\Models\NoteHonoraire;
use App\Models\Notification;
use App\Models\Observation;
use App\Models\Operation;
use App\Models\Payment;
use App\Models\Piece;
use App\Models\PieceType;
use App\Models\Rapport;
use App\Models\RapportStatus;
use App\Models\Signature;
use App\Models\Step;
use App\Models\Taux;
use App\Models\TypeDocument;
use App\Models\TypeIngredient;
use App\Models\TypeReparation;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class RapportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {
        // if (Auth::user()->role_id == 4) {
        $rapports = Rapport::where('dossier_id', $id)->with('dossier')->get();
        // } else {
        //     $rapports = Rapport::where('dossier_id', $id)->with('dossier')->latest()->get();
        // }
        return view('rapport.index', compact('rapports', 'id'));
    }

    public function documents($id)
    {
        $rapport = Rapport::whereId($id)->with('dossier', 'documents')->first();
        $docs = Document::where('dossier_id', $rapport->dossier_id)->whereHas('typedocument', function ($query) {
            $query->where('is_pdf', 0)->where('id', '!=', 9)->latest();
        })->with('rapports', function ($query) use ($id) {
            $query->where('rapport_id', $id);
        })->get();

        return view('rapport.documents', compact('docs', 'id'));
    }

    public function attachments(Request $request, $id)
    {
        $rapport = Rapport::whereId($id)->with('dossier', 'documents')->firstOrFail();

        $array_img = $request->img;
        $array_body = $request->body;
        $rapport->documents()->detach();

        for ($i = 0; $i < count($array_img); $i++) {
            if ($array_body[$i] != null) {
                $document = Document::whereId($array_img[$i])->firstOrFail();
                $rapport->documents()->attach($document, ['observation' => $array_body[$i]]);
            }
        }
        return redirect()->route('Rapport.show', $id);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($dossier_id)
    {
        $this->authorize('create', Rapport::class);
        $dossier = Dossier::with('vehiculemodel', 'company', 'shockpoint')->whereId($dossier_id)->with('document', function ($query) {
            $query->whereHas('typedocument', function ($query) {
                $query->where('is_pdf', 0)->where('id', '!=', 9)->latest();
            });
        })->withCount('shockpoint')->first();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $count = Facture::where('dossier_id', $dossier->id)->where(function ($query) {
            $query->where('devis_status_id', 2)->Orwhere('devis_status_id', 7);
        })->count();
        $oldrapport = Rapport::where('dossier_id', $dossier_id)->with('piece', 'taux')->latest()->first();
        if ($oldrapport) {
            if ($oldrapport->rapport_status_id == 4 || $oldrapport->rapport_status_id == 5) {
                return redirect()->back()->with('error', 'Rapport deja en cours');
            }
        }


        if (($dossier->type_expertise_id != 17) && ($count == 0 && $dossier->type_expertise_id != 14) && ($count == 0 && $dossier->mode_id != 7) && ($count == 0 && $dossier->mode_id != 2) && ($count == 0 && $dossier->mode_id != 3) && ($count == 0 && $dossier->mode_id != 6) && ($dossier->type_expertise_id != 16 && $dossier->mode_id != 7)) {
            return redirect()->back()->with('error', 'Besoin ou Attente Accord de Facture');
        }
        if ($dossier->shockpoint_count < 1) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Ajouter les Points de chock');
        }
        if (!$dossier->vehiculemodel) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Ajouter Modéle du Vehicule Au dossier ');
        }
        if ($dossier->type_expertise_id != 17) {
            if (!$dossier->intermidiaire_id ||  !$dossier->numero_police || !$dossier->numero_chassis || !$dossier->date_circulation  || !$dossier->kilometrage || !$dossier->puissance_fiscale || !$dossier->carburant_id) {
                return redirect()->route('Dossier.show', $dossier->id)
                    ->with('error', 'Un ou plusieurs champs sont vide (intermidiare,numero police,numero chassis,DMC,kilometrage,puissance fiscale, carburant');
            }
        }

        $rapport = Rapport::create([
            'dossier_id' => $dossier->id,
            'rapport_status_id' => 5
        ]);
        $status = RapportStatus::whereId(5)->first();
        $rapport->rapportstatus()->attach($status, ['user_id' => Auth::user()->id]);

        if ($oldrapport) {
            if ($oldrapport->piece) {

                foreach ($oldrapport->piece as $piece) {

                    $rapport->piece()->attach($piece, [
                        'qte' => $piece->pivot->qte, 'prix_unitaire' => $piece->pivot->prix_unitaire, 'gravite' => $piece->pivot->gravite, 'etat' => $piece->pivot->etat, 'vetuste' => $piece->pivot->vetuste ?? 0, 'remise' => $piece->pivot->remise ?? 0, 'montant_ht' => $piece->pivot->montant_ht,
                        'type_reparation_id' => $piece->pivot->type_reparation_id, 'operation_id' => $piece->pivot->operation_id, 'vehicule_model_id' => $dossier->vehicule_model_id
                    ]);
                    // $rapport->piece->pivot()->attach($piece, ['gravite' => $piece->pivot->gravite, 'etat' => $piece->pivot->etat, 'type_reparation_id' => $piece->pivot->type_reparation_id, 'operation_id' => $piece->pivot->operation_id, 'vehicule_model_id' => $piece->pivot->vehicule_model_id, 'qte' => $piece->pivot->qte, 'vetuste' => $piece->pivot->vetuste ?? 0, 'remise' => $piece->pivot->remise ?? 0, 'montant_ht' => $piece->pivot->montant_ht]);
                }
            }
            if ($oldrapport->taux) {
                $rapport->taux_id = $oldrapport->taux_id;
                $rapport->update();
            }
        } else {
            $devis = Devis::where('dossier_id', $dossier->id)->with('piece', 'taux')->where(function ($query) {
                $query->where('devis_status_id', 2)
                    ->orWhere('devis_status_id', 7);
            })->latest()->first();
            if ($devis) {
                if ($devis->piece) {
                    foreach ($devis->piece as $piece) {
                        $rapport->piece()->attach($piece, ['gravite' => $piece->pivot->gravite, 'etat' => $piece->pivot->etat, 'type_reparation_id' => $piece->pivot->type_reparation_id, 'operation_id' => $piece->pivot->operation_id, 'vehicule_model_id' => $piece->pivot->vehicule_model_id, 'qte' => $piece->pivot->qte, 'vetuste' => $piece->pivot->vetuste ?? 0, 'remise' => $piece->pivot->remise ?? 0, 'montant_ht' => $piece->pivot->montant_ht]);
                    }
                }
                if ($devis->taux) {
                    $rapport->taux_id = $devis->taux_id;
                    $rapport->update();
                }
            }
        }
        \App\Services\SidebarCache::clear();
        return redirect()->route('Rapport.show', $rapport->id);
    }

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

        $rapport = Rapport::whereId($request->rapport_id)->firstOrFail();
        $dossier = Dossier::whereId($rapport->dossier_id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }

        if ($request->has('points')) {
            $rapport->piecetype()->detach();
            $points = array_map("intval", explode(",", $request->points));
            $types = PieceType::whereIn('id', $points)->get();
            foreach ($types as $p) {
                $rapport->piecetype()->syncWithoutDetaching($p);
            }
        }

        return redirect()->back();
    }

    public function attach(Request $request)
    {
        try {
            $rapport = Rapport::whereId($request->rapport_id)->with('piece')->first();
            $rapport->piece()->detach();
            if ($request->has('piece')) {
                for ($i = 0; $i < count($request['piece']); $i++) {
                    $piece = Piece::findOrFail($request['libelle'][$i]);
                    if ($request['type'][$i] == 1) {
                        $montant = $piece->prix_unitaire * $request['qte'][$i];
                    } else {
                        if ($rapport->dossier->type_expertise_id == 14) {
                            $montant = $piece->prix_unitaire * $request['qte'][$i] + $piece->prix_unitaire * $request['qte'][$i] * 0.2;
                        } else {
                            $montant = $piece->prix_unitaire * $request['qte'][$i];
                        }
                    }
                    $montant2 = ($montant * $request['remise'][$i]) / 100;
                    $montant3 = ($montant * $request['vetuste'][$i]) / 100;
                    $montant1 = $montant - $montant2 - $montant3;

                    $rapport->piece()->attach($piece, [
                        'qte' => $request['qte'][$i], 'prix_unitaire' => $request['prix_unitaire'][$i], 'gravite' => $request['gravite'][$i], 'etat' => $request['etat'][$i],
                        'vetuste' => $request['vetuste'][$i], 'remise' => $request['remise'][$i], 'montant_ht' => $montant1,
                        'type_reparation_id' => $request['type'][$i], 'operation_id' => $request['operation'][$i], 'vehicule_model_id' => $rapport->dossier->vehicule_model_id
                    ]);
                }
            }
            \App\Services\SidebarCache::clear();
            return response()->json([
                'status' => true,
                'message' => 'Successfully',
            ], 200);
        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
        }
        return 'true';
    }

    public function pdf($id)
    {
        $rapport = Rapport::whereId($id)->with('document')->first();
        return view('rapport.pdf', compact('rapport'));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Rapport  $rapport
     * @return \Illuminate\Http\Response
     */
    public function send(Request $request)
    {
        //envoyer le rapport pdf a expert
        $this->authorize('create', Rapport::class);
        $rapport = Rapport::whereId($request->rapport_id)->with('piece', 'taux', 'piece.operation', 'piece.typereparation', 'documents')->withCount('documents')->firstOrFail();
        $dossier = Dossier::whereId($rapport->dossier_id)->with('rapport', 'company', 'rapport.piece', 'shockpoint', 'observation', 'contradictoire.adverse')->firstOrFail();
        $montant = Montant::where('dossier_id')->first();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }

        // $count = Facture::where('dossier_id', $dossier->id)->where(function ($query) {
        //     $query->where('devis_status_id', 2)
        //         ->orWhere('devis_status_id', 7);
        // })->count();

        $rapport->rapport_status_id = 4;
        $status = RapportStatus::whereId(4)->first();
        $rapport->rapportstatus()->attach($status, ['user_id' => Auth::user()->id]);
        $adpt = 0;
        $org = 0;
        $recup = 0;

        if ($dossier->mode_id != 2 && $dossier->mode_id != 3 && $dossier->mode_id != 6) {
            if (!$rapport->taux) {
                return redirect()->back()->with('error', 'Merci de saisir les Taux');
            }
            if (!$rapport->piece) {
                return redirect()->back()->with('error', 'Merci de affecter les piece');
            }
        }

        if ($dossier->type_expertise_id != 17) {
            if (!$dossier->intermidiaire_id ||  !$dossier->numero_police || !$dossier->numero_chassis || !$dossier->date_circulation  || !$dossier->kilometrage || !$dossier->puissance_fiscale || !$dossier->carburant_id) {
                return redirect()->route('Dossier.show', $dossier->id)
                    ->with('error', 'Un ou plusieurs champs sont vide (intermidiare,numero police,numero chassis,DMC,kilometrage,puissance fiscale, carburant');
            }
        }
        if ($dossier->typeexpertise->id == 4 || $dossier->type_expertise_id == 5 || $dossier->typeexpertise->id == 6 || $dossier->type_expertise_id == 7) {
            if (!$dossier->contradictoire) {
                return redirect()->route('Dossier.show', $dossier->id)
                    ->with('error', 'Merci de selectionner Expert Adverse ');
            }
            if ($dossier->type_expertise_id == 7 || $dossier->type_expertise_id == 5) {
                if (!$dossier->montant_accord_adverse) {
                    return redirect()->route('Dossier.show', $dossier->id)
                        ->with('error', 'Merci de saisir Montant Accord Adverse');
                }
            }
        }

        $admin = User::where('role_id', 4)->first();
        $meeting = Meeting::where('dossier_id', $dossier->id)->where('meeting_status_id', 3)->first();
        $facture = Facture::where('dossier_id', $dossier->id)->first();
        $devis = Devis::where('dossier_id', $dossier->id)->first();

        $sign = 0;
        $chock = Document::where('dossier_id', $dossier->id)->where('type_document_id', 18)->first();
        $observations = Observation::where('dossier_id', $dossier->id)->where('for_rapport', true)->get();
        $montantpieces = 0;
        $vet = 0;
        $tva = 0;
        $ttc = 0;
        $fr = 0;
        $ttl = 0;
        $fr = 0;
        $taux = 0;
        $montantclient = 0;
        $montantcompany = 0;
        $tvaa = 0;
        $tvaa2 = 0;
        $tvaa = 0;
        $tvaa2 = 0;
        $main01 = 0;
        $main02 = 0;
        $main03 = 0;
        $main04 = 0;
        $main05 = 0;
        $main06 = 0;
        $main07 = 0;
        $ingr = 0;
        $sum = 0;
        $rem = 0;
        $ht = 0;
        $remise = 0;
        $remisef = 0;
        $montantpieces = 0;
        foreach ($rapport->piece as $p) {
            if ($p->pivot->type_reparation_id == 1) {
                $recup += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
            if ($p->pivot->type_reparation_id == 2) {
                $adpt += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
            if ($p->pivot->type_reparation_id == 3) {
                $org += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
        }

        if ($dossier->type_expertise_id != 14 && $dossier->mode_id != 7) {

            if ($rapport->piece) {
                foreach ($rapport->piece as $piece) {
                    if ($piece->pivot->type_reparation_id == 1) {
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte);
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $remise = $remise + (($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise) / 100);
                        $vet = $vet + ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->vetuste / 100);
                    } else {
                        $rem = ($piece->pivot->qte * $piece->pivot->prix_unitaire) * ($piece->pivot->remise / 100);
                        $remise = $remise + $rem;
                        $tvaa = ($piece->pivot->prix_unitaire * $piece->pivot->qte - $rem) * 0.2;
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte - $rem) + $tvaa;
                        // $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        if ($rapport->taux) {
                            if ($rapport->taux->tva_deductible) {
                                $vet = $vet +   (($piece->pivot->qte * $piece->pivot->prix_unitaire) - $rem) * ($piece->pivot->vetuste / 100);
                            } else {
                                $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire - $rem + $tvaa)  * ($piece->pivot->vetuste / 100);
                            }
                        } else {
                            $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire - $rem) * ($piece->pivot->vetuste / 100);
                        }
                    }
                }
            }
            // else {
            //     return redirect()->back()->with('Merci de Ajouter Pieces au Rapport');
            // }
            // if ($rapport->taux) {
            //     if ($rapport->taux->tva_deductible) {
            //         $montantpieces = $montantpieces - $tvaa2;
            //     }
            // }
            // dd($tvaa2 , $montantpieces);

            if ($rapport->taux) {
                $remisep = ($rapport->taux->taux_mo_peinture * $rapport->taux->tp * $rapport->taux->remise_sur_total_mo_peinture) / 100;
                $remise = $remise + $remisep;
                $montantpieces = $montantpieces - $remisep;

                if ($rapport->taux->taux_ing) {
                    $taux_ing_metal = $rapport->taux->taux_ing_metal + $rapport->taux->taux_ing_metal * 0.2;
                    $taux_ing_metal_vernis = $rapport->taux->taux_ing_metal_vernis + $rapport->taux->taux_ing_metal_vernis * 0.2;
                    $taux_ing_nacre_vernis = $rapport->taux->taux_ing_nacre_vernis + $rapport->taux->taux_ing_nacre_vernis * 0.2;
                    $taux_ing_opaque = $rapport->taux->taux_ing_opaque + $rapport->taux->taux_ing_opaque * 0.2;
                    $taux_ing_opaque_vernis = $rapport->taux->taux_ing_opaque_vernis + $rapport->taux->taux_ing_opaque_vernis * 0.2;
                    $tva = $tvaa2 + $rapport->taux->taux_ing_opaque_vernis * 0.2 + $rapport->taux->taux_ing_opaque * 0.2 + $rapport->taux->taux_ing_nacre_vernis * 0.2 + $rapport->taux->taux_ing_metal_vernis * 0.2 + $rapport->taux->taux_ing_metal * 0.2;
                } else {
                    $taux_ing_metal = $rapport->taux->taux_ing_metal;
                    $taux_ing_metal_vernis = $rapport->taux->taux_ing_metal_vernis;
                    $taux_ing_nacre_vernis = $rapport->taux->taux_ing_nacre_vernis;
                    $taux_ing_opaque = $rapport->taux->taux_ing_opaque;
                    $taux_ing_opaque_vernis = $rapport->taux->taux_ing_opaque_vernis;
                    $tva = $tva + $tvaa2;
                }
                if ($rapport->taux->taux_tva) {
                    $main01 = $rapport->taux->taux_1 * $rapport->taux->t1 + $rapport->taux->taux_1 * $rapport->taux->t1 * 0.2;
                    $main02 = $rapport->taux->taux_2 * $rapport->taux->t2 + $rapport->taux->taux_2 * $rapport->taux->t2 * 0.2;
                    $main03 = $rapport->taux->taux_3 * $rapport->taux->t3 + $rapport->taux->taux_3 * $rapport->taux->t3 * 0.2;
                    $main04 = $rapport->taux->taux_mo_peinture * $rapport->taux->tp + $rapport->taux->taux_mo_peinture * $rapport->taux->tp * 0.2;
                    $main05 = $rapport->taux->taux_electricite * $rapport->taux->te + $rapport->taux->taux_electricite * $rapport->taux->te * 0.2;
                    $main06 = $rapport->taux->taux_controle * $rapport->taux->tc + $rapport->taux->taux_controle * $rapport->taux->tc * 0.2;
                    $main07 = $rapport->taux->taux_mecanique * $rapport->taux->tm + $rapport->taux->taux_mecanique * $rapport->taux->tm * 0.2;
                    $tva += $rapport->taux->taux_mecanique * $rapport->taux->tm * 0.2 + $rapport->taux->taux_controle * $rapport->taux->tc * 0.2 + $rapport->taux->taux_electricite * $rapport->taux->te * 0.2 + $rapport->taux->taux_mo_peinture * $rapport->taux->tp * 0.2 + $rapport->taux->taux_3 * $rapport->taux->t3 * 0.2 + $rapport->taux->taux_2 * $rapport->taux->t2 * 0.2 + $rapport->taux->taux_1 * $rapport->taux->t1 * 0.2;
                    $ingr = $taux_ing_metal + $taux_ing_metal_vernis + $taux_ing_nacre_vernis + $taux_ing_opaque + $taux_ing_opaque_vernis;
                    $sum =  $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                    $remisef = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                    $fr =  $rapport->taux->franchise + (($sum)  * ($rapport->taux->franchise_fix / 100));
                    $ttl = $sum;
                } else {
                    $main01 = $rapport->taux->taux_1 * $rapport->taux->t1;
                    $main02 = $rapport->taux->taux_2 * $rapport->taux->t2;
                    $main03 = $rapport->taux->taux_3 * $rapport->taux->t3;
                    $main04 = $rapport->taux->taux_mo_peinture * $rapport->taux->tp;
                    $main05 = $rapport->taux->taux_electricite * $rapport->taux->te;
                    $main06 = $rapport->taux->taux_controle * $rapport->taux->tc;
                    $main07 = $rapport->taux->taux_mecanique * $rapport->taux->tm;
                    $ingr = $taux_ing_metal + $taux_ing_metal_vernis + $taux_ing_nacre_vernis + $taux_ing_opaque + $taux_ing_opaque_vernis;
                    $sum =  $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                    $remisef = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                    $fr =  $rapport->taux->franchise + (($sum)  * ($rapport->taux->franchise_fix / 100));
                    $ttl = $sum;
                }
                //  dd($ttl);
                // dd($montantpieces);
                $ht = $ttl - $tva;
                if ($rapport->taux->vetuste) {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient =  $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient =  $fr;
                        $montantcompany = $ttl - $vet - $fr;
                    }
                } else {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient = $vet + $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient = $vet + $fr;
                        $montantcompany = $ttl  - $vet - $fr;
                    }
                }
            }
            // else {
            //     return redirect()->back()->with('Merci de Ajouter Taux au Rapport');
            // }
        } else {
            if ($rapport->piece) {
                foreach ($rapport->piece as $piece) {
                    if ($piece->pivot->type_reparation_id == 1) {
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte);
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $remise = $remise + (($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise) / 100);
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->vetuste / 100);
                    } else {
                        $tvaa = $piece->pivot->prix_unitaire * $piece->pivot->qte * 0.2;
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte) + $tvaa;
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $remise = $remise + ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire + ($piece->pivot->qte * $piece->pivot->prix_unitaire * 0.2)) * ($piece->pivot->vetuste / 100);
                    }
                }
            } else {
                return redirect()->back()->with('Merci de Ajouter Pieces au Rapport');
            }

            if ($rapport->taux) {
                // $montantpieces = $montantpieces - ($montantpieces * $rapport->taux->remise_piece / 100);
                $main01 =   $rapport->taux->forfait_mo_1;
                $main02 = $rapport->taux->forfait_mo_2;
                $main03 = $rapport->taux->forfait_mo_3;
                $main04 = $rapport->taux->forfait_peinture;
                $main05 = $rapport->taux->forfait_electricite;
                $main06 = $rapport->taux->forfait_controle;
                $main07 = $rapport->taux->forfait_mecanique;
                $ingr = $rapport->taux->forfait_ing_pieces;
                $sum = $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                $fr =  $rapport->taux->franchise + (($ttl)  * ($rapport->taux->franchise_fix / 100));
                $remisef = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                $ttl = $sum;
                $ht = $ttl - $tva;

                if ($rapport->taux->vetuste) {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient =  $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient =  $fr;
                        $montantcompany = $ttl - $vet - $fr;
                    }
                } else {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient = $vet + $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient = $vet + $fr;
                        $montantcompany = $ttl  - $vet - $fr;
                    }
                }
            } else {
                return redirect()->back()->with('Merci de Ajouter Taux au Rapport');
            }
        }
        $today = Carbon::now();
        $encours = Document::where('dossier_id', $dossier->id)->where('type_document_id', 7)->first();
        $apres = Document::where('dossier_id', $dossier->id)->where('type_document_id', 6)->first();
        $pdf = PDF::loadView('configuration.pdf.normalnew', compact('dossier', 'remise', 'apres', 'encours', 'ht', 'meeting', 'devis', 'facture', 'fr', 'vet', 'tva', 'observations', 'sign', 'rapport', 'chock', 'montantpieces', 'org', 'adpt', 'recup', 'ttl',  'main01', 'main02', 'main03', 'main04', 'main05', 'main06', 'main07', 'ingr', 'vet', 'montantclient', 'montantcompany'));
        $type = TypeDocument::whereId(10)->first();
        $filename = uniqid() . '.' . 'pdf';
        $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
        Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $pdf->output());
        $document =  Document::updateOrCreate(['dossier_id' => $dossier->id, 'type_document_id' => $type->id], [
            'path' => $path,
        ]);
        $rapport->document_id = $document->id;
        $rapport->update();
        $step = Step::whereId('12')->firstOrFail();
        $dossier->step()->attach($step, ['user_id' => $admin->id]);
        Notification::create([
            'user_id' => Auth::user()->id,
            'dossier_id' => $rapport->dossier->id,
            'body' => 'Rapport est envoyer a Expert pour Signature' . $dossier->ref
        ]);

        // return $pdf->stream();
        \App\Services\SidebarCache::clear();
        return redirect()->route('home')->with('success', 'Rapport est envoyer a Expert pour Signature');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Rapport  $rapport
     * @return \Illuminate\Http\Response
     */
    public function signature($id)
    {
        $this->authorize('update', Rapport::class);
        $rapport = Rapport::whereId($id)->first();
        $dossier = Dossier::whereId($rapport->dossier_id)->with('insured', 'rapport', 'garage', 'vehiculemodel.brand', 'opponent', 'guarantee', 'company', 'observation', 'status', 'mode', 'step', 'document', 'document.typedocument', 'devis', 'opponent.vehiculemodel.brand')
            ->with('document', function ($query) {
                $query->whereHas('typedocument', function ($query) {
                    $query->where('is_pdf', 0);
                });
            })->firstOrFail();
        $typedocuments = TypeDocument::where('is_pdf', '0')->whereHas('document', function ($query) use ($dossier) {
            $query->where('dossier_id', $dossier->id);
        })->get();
        // $typedocuments = TypeDocument::where('is_pdf', '0')->get();
        // $documents = Document::where('type_document_id', 1)->get();
        $observations = Observation::where('dossier_id', $dossier->id)->get();
        $doc = Document::where('type_document_id', 10)->where('dossier_id', $rapport->dossier_id)->latest()->first();

        return view('rapport.signature', compact('rapport', 'observations', 'dossier', 'typedocuments', 'doc'));
    }




    public function status(Request $request)
    {
        $this->authorize('update', Rapport::class);

        $rapport = Rapport::whereId($request->rapport_id)->with('piece', 'piece.operation', 'piece.typereparation', 'documents')->withCount('documents')->first();
        $dossier = Dossier::whereId($rapport->dossier_id)->with('company',  'shockpoint', 'observation', 'contradictoire.adverse')->firstOrFail();
        $type = TypeDocument::whereId(10)->first();

        $rp = Rapport::where('dossier_id', $dossier->id)->where('rapport_status_id', 2)->count();
        $observations = Observation::where('dossier_id', $dossier->id)->with('user')->where('for_rapport', 1)->get();
        $montant = Montant::where('dossier_id', $dossier->id)->first();
        $chock = Document::where('dossier_id', $dossier->id)->where('type_document_id', 18)->first();
        if ($dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $adpt = 0;
        $org = 0;
        $recup = 0;
        $chock = Document::where('dossier_id', $dossier->id)->where('type_document_id', 18)->first();
        $observations = Observation::where('dossier_id', $dossier->id)->where('for_rapport', 1)->get();
        $position = 0;


        // if (!$rapport->taux) {
        //     return redirect()->back()->with('error', 'Merci de saisir les Taux');
        // }
        // if (!$rapport->piece) {
        //     return redirect()->back()->with('error', 'Merci de affecter les piece');
        // }
        $devis = Devis::where('dossier_id', $dossier->id)->first();
        $admin = User::where('role_id', 4)->first();
        $meeting = Meeting::where('dossier_id', $dossier->id)->where('meeting_status_id', 3)->first();
        $facture = Facture::where('dossier_id', $dossier->id)->first();
        $sign = 0;
        $chock = Document::where('dossier_id', $dossier->id)->where('type_document_id', 18)->first();
        $observations = Observation::where('dossier_id', $dossier->id)->where('for_rapport', true)->get();
        $vet = 0;
        $tva = 0;
        $ttc = 0;
        $fr = 0;
        $ttl = 0;
        $fr = 0;
        $taux = 0;
        $montantclient = 0;
        $montantcompany = 0;
        $tvaa = 0;
        $tvaa2 = 0;
        $tvaa = 0;
        $tvaa2 = 0;
        $main01 = 0;
        $main02 = 0;
        $main03 = 0;
        $main04 = 0;
        $main05 = 0;
        $main06 = 0;
        $main07 = 0;
        $ingr = 0;
        $sum = 0;
        $rem = 0;
        $remise = 0;
        $remisef = 0;
        $ht = 0;
        $montantpieces = 0;

        foreach ($rapport->piece as $p) {
            if ($p->pivot->type_reparation_id == 1) {
                $recup += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
            if ($p->pivot->type_reparation_id == 2) {
                $adpt += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
            if ($p->pivot->type_reparation_id == 3) {
                $org += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
        }

        if ($dossier->type_expertise_id != 14 && $dossier->mode_id != 7) {

            if ($rapport->piece) {
                foreach ($rapport->piece as $piece) {
                    if ($piece->pivot->type_reparation_id == 1) {
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte);
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $remise = $remise + (($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise) / 100);
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->vetuste / 100);
                    } else {
                        $rem = ($piece->pivot->qte * $piece->pivot->prix_unitaire) * ($piece->pivot->remise / 100);
                        $remise = $remise + $rem;

                        $tvaa = ($piece->pivot->prix_unitaire * $piece->pivot->qte - $rem) * 0.2;
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte - $rem) + $tvaa;

                        // $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        if ($rapport->taux) {
                            if ($rapport->taux->tva_deductible) {
                                $vet = $vet +   (($piece->pivot->qte * $piece->pivot->prix_unitaire) - $rem) * ($piece->pivot->vetuste / 100);
                            } else {
                                $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire - $rem + $tvaa)  * ($piece->pivot->vetuste / 100);
                            }
                        } else {
                            $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire - $rem) * ($piece->pivot->vetuste / 100);
                        }
                    }
                }
            }
            // else {
            //     return redirect()->back()->with('Merci de Ajouter Pieces au Rapport');
            // }
            // if ($rapport->taux) {
            //     if ($rapport->taux->tva_deductible) {
            //         $montantpieces = $montantpieces - $tvaa2;
            //     }
            // }
            // dd($tvaa2 , $montantpieces);

            if ($rapport->taux) {
                $remisep = ($rapport->taux->taux_mo_peinture * $rapport->taux->tp * $rapport->taux->remise_sur_total_mo_peinture) / 100;
                $montantpieces = $montantpieces - $remisep;
                $remise = $remise + $remisep;

                if ($rapport->taux->taux_ing) {
                    $taux_ing_metal = $rapport->taux->taux_ing_metal + $rapport->taux->taux_ing_metal * 0.2;
                    $taux_ing_metal_vernis = $rapport->taux->taux_ing_metal_vernis + $rapport->taux->taux_ing_metal_vernis * 0.2;
                    $taux_ing_nacre_vernis = $rapport->taux->taux_ing_nacre_vernis + $rapport->taux->taux_ing_nacre_vernis * 0.2;
                    $taux_ing_opaque = $rapport->taux->taux_ing_opaque + $rapport->taux->taux_ing_opaque * 0.2;
                    $taux_ing_opaque_vernis = $rapport->taux->taux_ing_opaque_vernis + $rapport->taux->taux_ing_opaque_vernis * 0.2;
                    $tva = $tvaa2 + $rapport->taux->taux_ing_opaque_vernis * 0.2 + $rapport->taux->taux_ing_opaque * 0.2 + $rapport->taux->taux_ing_nacre_vernis * 0.2 + $rapport->taux->taux_ing_metal_vernis * 0.2 + $rapport->taux->taux_ing_metal * 0.2;
                } else {
                    $taux_ing_metal = $rapport->taux->taux_ing_metal;
                    $taux_ing_metal_vernis = $rapport->taux->taux_ing_metal_vernis;
                    $taux_ing_nacre_vernis = $rapport->taux->taux_ing_nacre_vernis;
                    $taux_ing_opaque = $rapport->taux->taux_ing_opaque;
                    $taux_ing_opaque_vernis = $rapport->taux->taux_ing_opaque_vernis;
                    $tva = $tva + $tvaa2;
                }
                if ($rapport->taux->taux_tva) {
                    $main01 = $rapport->taux->taux_1 * $rapport->taux->t1 + $rapport->taux->taux_1 * $rapport->taux->t1 * 0.2;
                    $main02 = $rapport->taux->taux_2 * $rapport->taux->t2 + $rapport->taux->taux_2 * $rapport->taux->t2 * 0.2;
                    $main03 = $rapport->taux->taux_3 * $rapport->taux->t3 + $rapport->taux->taux_3 * $rapport->taux->t3 * 0.2;
                    $main04 = $rapport->taux->taux_mo_peinture * $rapport->taux->tp + $rapport->taux->taux_mo_peinture * $rapport->taux->tp * 0.2;
                    $main05 = $rapport->taux->taux_electricite * $rapport->taux->te + $rapport->taux->taux_electricite * $rapport->taux->te * 0.2;
                    $main06 = $rapport->taux->taux_controle * $rapport->taux->tc + $rapport->taux->taux_controle * $rapport->taux->tc * 0.2;
                    $main07 = $rapport->taux->taux_mecanique * $rapport->taux->tm + $rapport->taux->taux_mecanique * $rapport->taux->tm * 0.2;
                    $tva += $rapport->taux->taux_mecanique * $rapport->taux->tm * 0.2 + $rapport->taux->taux_controle * $rapport->taux->tc * 0.2 + $rapport->taux->taux_electricite * $rapport->taux->te * 0.2 + $rapport->taux->taux_mo_peinture * $rapport->taux->tp * 0.2 + $rapport->taux->taux_3 * $rapport->taux->t3 * 0.2 + $rapport->taux->taux_2 * $rapport->taux->t2 * 0.2 + $rapport->taux->taux_1 * $rapport->taux->t1 * 0.2;
                    $ingr = $taux_ing_metal + $taux_ing_metal_vernis + $taux_ing_nacre_vernis + $taux_ing_opaque + $taux_ing_opaque_vernis;
                    $sum =  $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                    $remisef = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                    $fr =  $rapport->taux->franchise + (($sum)  * ($rapport->taux->franchise_fix / 100));
                    $ttl = $sum;
                } else {
                    $main01 = $rapport->taux->taux_1 * $rapport->taux->t1;
                    $main02 = $rapport->taux->taux_2 * $rapport->taux->t2;
                    $main03 = $rapport->taux->taux_3 * $rapport->taux->t3;
                    $main04 = $rapport->taux->taux_mo_peinture * $rapport->taux->tp;
                    $main05 = $rapport->taux->taux_electricite * $rapport->taux->te;
                    $main06 = $rapport->taux->taux_controle * $rapport->taux->tc;
                    $main07 = $rapport->taux->taux_mecanique * $rapport->taux->tm;
                    $ingr = $taux_ing_metal + $taux_ing_metal_vernis + $taux_ing_nacre_vernis + $taux_ing_opaque + $taux_ing_opaque_vernis;
                    $sum =  $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                    $remisef = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                    $fr =  $rapport->taux->franchise + (($sum)  * ($rapport->taux->franchise_fix / 100));
                    $ttl = $sum;
                }
                //  dd($ttl);
                // dd($montantpieces);
                $ht = $ttl - $tva;
                if ($rapport->taux->vetuste) {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient =  $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient =  $fr;
                        $montantcompany = $ttl - $vet - $fr;
                    }
                } else {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient = $vet + $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient = $vet + $fr;
                        $montantcompany = $ttl  - $vet - $fr;
                    }
                }
            }
            // else {
            //     return redirect()->back()->with('Merci de Ajouter Taux au Rapport');
            // }
        } else {
            if ($rapport->piece) {
                foreach ($rapport->piece as $piece) {
                    if ($piece->pivot->type_reparation_id == 1) {
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte);
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $remise = $remise + (($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise) / 100);
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->vetuste / 100);
                    } else {
                        $tvaa = $piece->pivot->prix_unitaire * $piece->pivot->qte * 0.2;
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte) + $tvaa;
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        $remise = $remise + $rem;
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire + ($piece->pivot->qte * $piece->pivot->prix_unitaire * 0.2)) * ($piece->pivot->vetuste / 100);
                    }
                }
            } else {
                return redirect()->back()->with('Merci de Ajouter Pieces au Rapport');
            }

            if ($rapport->taux) {
                // $montantpieces = $montantpieces - ($montantpieces * $rapport->taux->remise_piece / 100);
                $main01 =   $rapport->taux->forfait_mo_1;
                $main02 = $rapport->taux->forfait_mo_2;
                $main03 = $rapport->taux->forfait_mo_3;
                $main04 = $rapport->taux->forfait_peinture;
                $main05 = $rapport->taux->forfait_electricite;
                $main06 = $rapport->taux->forfait_controle;
                $main07 = $rapport->taux->forfait_mecanique;
                $ingr = $rapport->taux->forfait_ing_pieces;
                $sum = $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                $fr =  $rapport->taux->franchise + (($ttl)  * ($rapport->taux->franchise_fix / 100));
                $remisef = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                $ttl = $sum;
                $ht = $ttl - $tva;
                if ($rapport->taux->vetuste) {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient =  $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient =  $fr;
                        $montantcompany = $ttl - $vet - $fr;
                    }
                } else {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient = $vet + $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient = $vet + $fr;
                        $montantcompany = $ttl  - $vet - $fr;
                    }
                }
            } else {
                return redirect()->back()->with('Merci de Ajouter Taux au Rapport');
            }
        }

        $today = Carbon::now();



        if ($montant) {
            $montant->montant_rapport = $ttl;
            $montant->update();
        } else {
            Montant::create([
                'dossier_id' => $dossier->id,
                'montant_rapport' => $ttl
            ]);
        }
        if ($rapport->rapport_status_id == 2) {
            if ($request->input('action') == 2) {

                $rapport->rapport_status_id = 3;
                $rapport->update();
                $body = "A Envoyer Rapport :" . $rapport->dossier->ref;
                Notification::create([
                    'user_id' => Auth::user()->id,
                    'dossier_id' => $rapport->dossier->id,
                    'body' => $body
                ]);
                \App\Services\SidebarCache::clear();
                return redirect()->route('home')->with('success', 'Rapport Est Envoyer ');
            }
        }


        if ($rapport->rapport_status_id === 4) {
            if ($request->input('action') == 0) {
                $request->validate(['observation' => 'required']);
                Observation::create(['observation' => $request->observation, 'dossier_id' => $dossier->id, 'user_id' => Auth::user()->id]);
                $pdf = Document::where('type_document_id', 10)->where('dossier_id', $rapport->dossier_id)->first();
                $rapport->rapport_status_id = 1;
                $rapport->update();
                $body = "A Refuser ce Rapport  :" . $rapport->dossier->ref;
                Notification::create([
                    'user_id' => Auth::user()->id,
                    'dossier_id' => $rapport->dossier->id,
                    'body' => $body
                ]);
                $status = RapportStatus::whereId(1)->first();
                $rapport->rapportstatus()->attach($status, ['user_id' => Auth::user()->id]);
                \App\Services\SidebarCache::clear();
                return redirect()->route('home')->with('success', 'Rapport Est Refuser');
            } else if ($request->input('action') == 1) {
                $this->authorize('signer', Rapport::class);
                // $note = NoteHonoraire::where('company_id', $dossier->company_id)->where('type_expertise_id', $dossier->type_expertise_id)->first();
                // if (!$note) {
                //     return redirect()->back()->with('error', 'Il faut ajouter une nouveau note honoraire avec assurance et type de dossier');
                // }
                $rapport->rapport_status_id = 2;
                $rapport->update();
                $sign = 1;
                if ($request->position == 1) {
                    $position = 1;
                } else {

                    $position = 2;
                }
                $encours = Document::where('dossier_id', $dossier->id)->where('type_document_id', 7)->first();
                $apres = Document::where('dossier_id', $dossier->id)->where('type_document_id', 6)->first();
                $pdf = PDF::loadView('configuration.pdf.normalnew', compact('dossier', 'remise', 'apres', 'encours', 'meeting', 'devis', 'facture', 'fr', 'vet', 'tva', 'ht', 'observations', 'sign', 'rapport', 'chock', 'montantpieces', 'org', 'adpt', 'recup', 'ttl',  'main01', 'main02', 'main03', 'main04', 'main05', 'main06', 'main07', 'ingr', 'vet', 'montantclient', 'montantcompany', 'position'));
                $filename = uniqid() . '.' . 'pdf';
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $pdf->output());
                $document =  Document::updateOrCreate(['dossier_id' => $dossier->id, 'type_document_id' => $type->id], [
                    'path' => $path,
                ]);
                $rapport->document_id = $document->id;
                $rapport->update();
                $step = Step::whereId(12)->first();
                $dossier->step()->attach($step, ['user_id' => Auth::user()->id]);
                $status = RapportStatus::whereId(2)->first();
                $rapport->rapportstatus()->attach($status, ['user_id' => Auth::user()->id]);
                $dossier->step_id = $step->id;
                $dossier->update = 1; 
                $dossier->date_fin = now();
                $dossier->save();
                Log::info('update is 1');
                $status = DossierStatus::whereId(3)->first();
                $dossier->dossierstatus()->attach($status);
                $body = "A Signer Rapport  :" . $rapport->dossier->ref;
                Notification::create([
                    'user_id' => Auth::user()->id,
                    'dossier_id' => $rapport->dossier->id,
                    'body' => $body
                ]);

                \App\Services\SidebarCache::clear();
                return redirect()->route('home')->with('success', 'Rapport Est Signer Avec Succés');
            }
        }


        return redirect()->route('Dossier.show', $dossier->id);
    }

    public function regenerate($id)
    {

        $rapport = Rapport::whereId($id)->firstOrFail();
        if ($rapport->rapport_status_id == 2 || $rapport->rapport_status_id == 3) {
            return redirect()->back()->with('error', 'Rapport est Déja Signer');
        }

        // if ($rapport->rapport_status_id == 2 || $rapport->rapport_status_id == 3) {
        //     $sign = 1;
        // } else {}
        $sign = 0;
        $remise = 0;

        $rapport = Rapport::with('piece', 'piece.typereparation', 'piece.operation', 'taux', 'documents')->withCount('documents')->whereId($id)->latest()->first();
        $dossier = Dossier::whereId($rapport->dossier_id)->with('document', 'company', 'shockpoint', 'contradictoire.adverse')->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        // if (!$rapport->taux) {
        //     return redirect()->back()->with('error', 'Merci de saisir les Taux');
        // }
        // if (!$rapport->piece) {
        //     return redirect()->back()->with('error', 'Merci de affecter les piece');
        // }
        $devis = Devis::where('dossier_id', $dossier->id)->first();
        $facture = Facture::where('dossier_id', $dossier->id)->first();
        $adpt = 0;
        $org = 0;
        $recup = 0;
        $montantpieces = 0;
        $vet = 0;
        $tva = 0;
        $ttc = 0;
        $fr = 0;
        $ttl = 0;
        $fr = 0;
        $taux = 0;
        $montantclient = 0;
        $montantcompany = 0;
        $tvaa = 0;
        $tvaa2 = 0;
        $main01 = 0;
        $main02 = 0;
        $main03 = 0;
        $main04 = 0;
        $main05 = 0;
        $main06 = 0;
        $main07 = 0;
        $ingr = 0;
        $sum = 0;
        $rem = 0;
        $ht = 0;
        $montantpieces = 0;
        $chock = Document::where('dossier_id', $dossier->id)->where('type_document_id', 18)->first();
        $observations = Observation::where('dossier_id', $dossier->id)->where('for_rapport', 1)->get();
        foreach ($rapport->piece as $p) {
            if ($p->pivot->type_reparation_id == 1) {
                $recup += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
            if ($p->pivot->type_reparation_id == 2) {
                $adpt += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
            if ($p->pivot->type_reparation_id == 3) {
                $org += $p->pivot->prix_unitaire * $p->pivot->qte;
            }
        }
        if ($dossier->type_expertise_id != 14 && $dossier->mode_id != 7) {

            if ($rapport->piece) {
                foreach ($rapport->piece as $piece) {
                    if ($piece->pivot->type_reparation_id == 1) {
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte);
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->vetuste / 100);
                        $remise = $remise + (($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise) / 100);
                    } else {
                        $rem = ($piece->pivot->qte * $piece->pivot->prix_unitaire) * ($piece->pivot->remise / 100);

                        $tvaa = ($piece->pivot->prix_unitaire * $piece->pivot->qte - $rem) * 0.2;
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte - $rem) + $tvaa;
                        $remise = $remise + $rem;

                        // $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        if ($rapport->taux) {
                            if ($rapport->taux->tva_deductible) {
                                $vet = $vet +   (($piece->pivot->qte * $piece->pivot->prix_unitaire) - $rem) * ($piece->pivot->vetuste / 100);
                            } else {
                                $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire - $rem + $tvaa)  * ($piece->pivot->vetuste / 100);
                            }
                        } else {
                            $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire - $rem) * ($piece->pivot->vetuste / 100);
                        }
                    }
                }
            }

            if ($rapport->taux) {
                $remisep = ($rapport->taux->taux_mo_peinture * $rapport->taux->tp * $rapport->taux->remise_sur_total_mo_peinture) / 100;
                $montantpieces = $montantpieces - $remisep;
                $remise = $remise + $remisep;

                if ($rapport->taux->taux_ing) {
                    $taux_ing_metal = $rapport->taux->taux_ing_metal + $rapport->taux->taux_ing_metal * 0.2;
                    $taux_ing_metal_vernis = $rapport->taux->taux_ing_metal_vernis + $rapport->taux->taux_ing_metal_vernis * 0.2;
                    $taux_ing_nacre_vernis = $rapport->taux->taux_ing_nacre_vernis + $rapport->taux->taux_ing_nacre_vernis * 0.2;
                    $taux_ing_opaque = $rapport->taux->taux_ing_opaque + $rapport->taux->taux_ing_opaque * 0.2;
                    $taux_ing_opaque_vernis = $rapport->taux->taux_ing_opaque_vernis + $rapport->taux->taux_ing_opaque_vernis * 0.2;
                    $tva = $tvaa2 + $rapport->taux->taux_ing_opaque_vernis * 0.2 + $rapport->taux->taux_ing_opaque * 0.2 + $rapport->taux->taux_ing_nacre_vernis * 0.2 + $rapport->taux->taux_ing_metal_vernis * 0.2 + $rapport->taux->taux_ing_metal * 0.2;
                } else {
                    $taux_ing_metal = $rapport->taux->taux_ing_metal;
                    $taux_ing_metal_vernis = $rapport->taux->taux_ing_metal_vernis;
                    $taux_ing_nacre_vernis = $rapport->taux->taux_ing_nacre_vernis;
                    $taux_ing_opaque = $rapport->taux->taux_ing_opaque;
                    $taux_ing_opaque_vernis = $rapport->taux->taux_ing_opaque_vernis;
                    $tva = $tva + $tvaa2;
                }
                if ($rapport->taux->taux_tva) {
                    $main01 = $rapport->taux->taux_1 * $rapport->taux->t1 + $rapport->taux->taux_1 * $rapport->taux->t1 * 0.2;
                    $main02 = $rapport->taux->taux_2 * $rapport->taux->t2 + $rapport->taux->taux_2 * $rapport->taux->t2 * 0.2;
                    $main03 = $rapport->taux->taux_3 * $rapport->taux->t3 + $rapport->taux->taux_3 * $rapport->taux->t3 * 0.2;
                    $main04 = $rapport->taux->taux_mo_peinture * $rapport->taux->tp + $rapport->taux->taux_mo_peinture * $rapport->taux->tp * 0.2;
                    $main05 = $rapport->taux->taux_electricite * $rapport->taux->te + $rapport->taux->taux_electricite * $rapport->taux->te * 0.2;
                    $main06 = $rapport->taux->taux_controle * $rapport->taux->tc + $rapport->taux->taux_controle * $rapport->taux->tc * 0.2;
                    $main07 = $rapport->taux->taux_mecanique * $rapport->taux->tm + $rapport->taux->taux_mecanique * $rapport->taux->tm * 0.2;
                    $tva += $rapport->taux->taux_mecanique * $rapport->taux->tm * 0.2 + $rapport->taux->taux_controle * $rapport->taux->tc * 0.2 + $rapport->taux->taux_electricite * $rapport->taux->te * 0.2 + $rapport->taux->taux_mo_peinture * $rapport->taux->tp * 0.2 + $rapport->taux->taux_3 * $rapport->taux->t3 * 0.2 + $rapport->taux->taux_2 * $rapport->taux->t2 * 0.2 + $rapport->taux->taux_1 * $rapport->taux->t1 * 0.2;
                    $ingr = $taux_ing_metal + $taux_ing_metal_vernis + $taux_ing_nacre_vernis + $taux_ing_opaque + $taux_ing_opaque_vernis;
                    $sum =  $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                    $remise = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                    $fr =  $rapport->taux->franchise + (($sum)  * ($rapport->taux->franchise_fix / 100));
                    $ttl = $sum;
                } else {
                    $main01 = $rapport->taux->taux_1 * $rapport->taux->t1;
                    $main02 = $rapport->taux->taux_2 * $rapport->taux->t2;
                    $main03 = $rapport->taux->taux_3 * $rapport->taux->t3;
                    $main04 = $rapport->taux->taux_mo_peinture * $rapport->taux->tp;
                    $main05 = $rapport->taux->taux_electricite * $rapport->taux->te;
                    $main06 = $rapport->taux->taux_controle * $rapport->taux->tc;
                    $main07 = $rapport->taux->taux_mecanique * $rapport->taux->tm;
                    $ingr = $taux_ing_metal + $taux_ing_metal_vernis + $taux_ing_nacre_vernis + $taux_ing_opaque + $taux_ing_opaque_vernis;
                    $sum =  $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                    $remise = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                    $fr =  $rapport->taux->franchise + (($sum)  * ($rapport->taux->franchise_fix / 100));
                    $ttl = $sum;
                }
                //  dd($ttl);
                // dd($montantpieces);
                $ht = $ttl - $tva;
                if ($rapport->taux->vetuste) {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient =  $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient =  $fr;
                        $montantcompany = $ttl - $vet - $fr;
                    }
                } else {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient = $vet + $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient = $vet + $fr;
                        $montantcompany = $ttl  - $vet - $fr;
                    }
                }
            }
            // else {
            //     return redirect()->back()->with('Merci de Ajouter Taux au Rapport');
            // }
        } else {
            if ($rapport->piece) {
                foreach ($rapport->piece as $piece) {
                    if ($piece->pivot->type_reparation_id == 1) {
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte);
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);

                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->vetuste / 100);
                    } else {
                        $tvaa = $piece->pivot->prix_unitaire * $piece->pivot->qte * 0.2;
                        $montantpieces = $montantpieces + ($piece->pivot->prix_unitaire * $piece->pivot->qte) + $tvaa;
                        $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        $vet = $vet +   ($piece->pivot->qte * $piece->pivot->prix_unitaire + ($piece->pivot->qte * $piece->pivot->prix_unitaire * 0.2)) * ($piece->pivot->vetuste / 100);
                    }
                }
            } else {
                return redirect()->back()->with('Merci de Ajouter Pieces au Rapport');
            }

            if ($rapport->taux) {
                // $montantpieces = $montantpieces - ($montantpieces * $rapport->taux->remise_piece / 100);
                $main01 =   $rapport->taux->forfait_mo_1;
                $main02 = $rapport->taux->forfait_mo_2;
                $main03 = $rapport->taux->forfait_mo_3;
                $main04 = $rapport->taux->forfait_peinture;
                $main05 = $rapport->taux->forfait_electricite;
                $main06 = $rapport->taux->forfait_controle;
                $main07 = $rapport->taux->forfait_mecanique;
                $ingr = $rapport->taux->forfait_ing_pieces;
                $sum = $main01 + $main02 + $main03 + $main04 + $main05 + $main06 + $main07 + $ingr + $montantpieces;
                $fr =  $rapport->taux->franchise + (($ttl)  * ($rapport->taux->franchise_fix / 100));
                $remise = $rapport->taux->remise_facture + ($sum * ($rapport->taux->remise_facture1 / 100));
                $ttl = $sum;
                $ht = $ttl - $tva;
                if ($rapport->taux->vetuste) {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient =  $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient =  $fr;
                        $montantcompany = $ttl - $vet - $fr;
                    }
                } else {

                    if ($rapport->taux->tva_deductible) {
                        $montantclient = $vet + $fr + $tva;
                        $montantcompany = $ttl - $tva - $vet - $fr;
                    } else {
                        $montantclient = $vet + $fr;
                        $montantcompany = $ttl  - $vet - $fr;
                    }
                }
            } else {
                return redirect()->back()->with('Merci de Ajouter Taux au Rapport');
            }
        }
        $meeting = Meeting::where('dossier_id', $dossier->id)->where('meeting_status_id', 3)->first();

        $today = Carbon::now();
        $position = 0;
        $type = TypeDocument::whereId(10)->first();
        $encours = Document::where('dossier_id', $dossier->id)->where('type_document_id', 7)->first();
        $apres = Document::where('dossier_id', $dossier->id)->where('type_document_id', 6)->first();
        $pdf = PDF::loadView('configuration.pdf.normalnew', compact('dossier', 'remise', 'apres', 'encours', 'ht', 'devis', 'fr', 'vet', 'tva', 'observations', 'sign', 'rapport', 'chock', 'montantpieces', 'org', 'adpt', 'recup', 'ttl',  'main01', 'main02', 'main03', 'main04', 'main05', 'main06', 'main07', 'ingr', 'vet', 'montantclient', 'montantcompany', 'facture', 'meeting', 'position'));
        $filename = uniqid() . '.' . 'pdf';
        $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
        Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $pdf->output());
        $document =  Document::updateOrCreate(['dossier_id' => $dossier->id, 'type_document_id' => $type->id], [
            'path' => $path,
        ]);
        $rapport->document_id = $document->id;
        $rapport->update();
        \App\Services\SidebarCache::clear();
        return redirect()->back()->with('success', 'Rapport est Regénerer Avec Succés');
    }

    public function show($id)
    {

        $rapport = Rapport::whereId($id)->with('taux', 'piecetype')->first();
        $dossier = Dossier::whereId($rapport->dossier_id)->with('insured', 'rapport', 'currency', 'garage', 'vehiculemodel.brand', 'opponent', 'guarantee', 'company', 'observation', 'status', 'mode', 'step', 'document', 'document.typedocument', 'devis', 'opponent.vehiculemodel.brand')
            ->with('document', function ($query) {
                $query->whereHas('typedocument', function ($query) {
                    $query->where('is_pdf', 0);
                });
            })->firstOrFail();
        $typedocuments = TypeDocument::where('is_pdf', '0')->whereHas('document', function ($query) use ($rapport) {
            $query->where('dossier_id', $rapport->dossier_id);
        })->get();

        // if($rapport->rapport_status_id == 3 ||$rapport->rapport_status_id == 2 ){
        //     return redirect()->route('rapport.signature',$rapport->id);
        // }
        $types = TypeReparation::all();
        $piecetypes = PieceType::where('svg', 1)->get();
        $typeingredients = TypeIngredient::all();
        // $taux = Taux::where('rapport_id', $rapport->id)->with('typeingredient')->first();
        $array = [];
        $array2 = [];
        $operations = Operation::all();
        if ($rapport->piece) {
            $collection = Rapport::whereId($rapport->id)->with('piece', 'pieceType')->first();
            foreach ($rapport->piece as $p) {
                array_push($array, $p->id);
                array_push($array2, $p->pivot->qte);
            }
        }

        if (isset($dossier->vehiculemodel)) {
            $pieces = Piece::where('vehicule_model_id', $dossier->vehicule_model_id)->whereNotIn('id', $array)->with('piecetype', 'rapport')->whereHas('rapport')->get();
            $rapportpieces = Rapport::whereId($rapport->id)->with('piece', 'pieceType')->first();
            $rapportpiecescount = Piece::where('vehicule_model_id', $dossier->vehiculemodel->id)->whereHas('rapport', function ($query) use ($rapport) {
                $query->where('rapport_id', $rapport->id);
            })->count();
        } else {
            $pieces = [];
            $rapportpieces = [];
            $rapportpiecescount = 0;
        }

        // dd($pieces);
        // $devis = Devis::where('dossier_id',$dossier->id)->with('taux','piece')
        // ->where('devis_status_id',2)
        // ->Orwhere('devis_status_id',7)->latest()
        // ->first();

        return view('rapport.create', compact('dossier', 'types', 'operations', 'typedocuments', 'rapport', 'typeingredients', 'pieces', 'collection', 'array', 'array2', 'piecetypes'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Rapport  $rapport
     * @return \Illuminate\Http\Response
     */
    public function forfait($id)
    {
        $doc = Document::whereId($id)->where('type_document_id', 16)->first();
        return view('rapport.forfait', compact('doc'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Rapport  $rapport
     * @return \Illuminate\Http\Response
     */
}
