<?php

namespace App\Http\Controllers;

use App\Mail\SendAccordMail;
use App\Models\Devis;
use App\Models\DevisStatus;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Mode;
use App\Models\Montant;
use App\Models\Notification;
use App\Models\Observation;
use App\Models\Operation;
use App\Models\Piece;
use App\Models\PieceType;
use App\Models\Seuil;
use App\Models\Step;
use App\Models\TypeDocument;
use App\Models\TypeIngredient;
use App\Models\TypeReparation;
use App\Models\User;
use Carbon\Carbon;
use Image;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Gate;
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 Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Framework\Constraint\Operator;
use Termwind\Components\Dd;

class DevisController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {
        $this->authorize('viewAny', Devis::class);

        $deviss = Devis::where('dossier_id', $id)->with('status', 'dossier')->latest()->get();
        if (!$deviss) {
            $dossier = Dossier::whereId($id)->firstOrFail();
            return view('devis.create', compact('dossier'));
        }
        return view('devis.index', compact('deviss', 'id'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $this->authorize('create', Devis::class);
        $dossier = Dossier::whereId($id)->with('step', 'company', 'typeexpertise', 'guarantee', 'devis')->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 ');
        }

        $docbase = Document::where('dossier_id', $id)->whereIn('type_document_id', [1, 2, 3])->count();

        if ($docbase == 0) {
            return redirect()->back()->with('error', 'Svp de Ajouter Documents de Base');
        }

        $devis = Devis::where('dossier_id', $dossier->id)->latest()->first();
        // if ($devis) {
        //     if ($devis->devis_status_id == 4) {
        //         return redirect()->back()->with('error', 'Svp de Traiter devis encours');
        //     }
        // }
        if (!$dossier->vehiculemodel) {
            return redirect()->back()->with('error', 'Svp de Ajouter Modele du Vehicule ');
        }
        if (!$dossier->typeexpertise) {
            return redirect()->back()->with('error', 'Svp de Ajouter Type Expertise Avant la Creation du Devis ');
        }
        if (!$dossier->guarantee) {
            return redirect()->back()->with('error', 'Svp de Ajouter Garantie Avant la Creation du Devis ');
        }
        if ($dossier->mode_id == 2 || $dossier->mode_id == 3) {
            if (!$dossier->valeurneuf) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur A Neuf');
            }
            if (!$dossier->valeuradire) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur A Dire');
            }
            if (!$dossier->horssinistre) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur Hors Sinistre');
            }
            if (!$dossier->valeurepave) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur Epavee');
            }
            if (!$dossier->valeurvenale) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur Venale');
            }
        }
        // $step = DB::table('step_dossier')
        //     ->where('dossier_id', $dossier->id)
        //     ->latest()->first();
        // if (Auth::user()->id != $step->user_id) {
        //     return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Vous avez pas le droit de apporter des modification a ce dossier maintenant');
        // }
        return view('devis.create', compact('dossier'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $this->authorize('create', Devis::class);

        $validator = Validator::make(
            $request->all(),
            [
                'files' => 'required',
                'montant_devis' => 'required|numeric',
                'ref' => 'nullable|string',
                'date' => 'date|required',
                'files.*' => 'required|file'
            ],
            [
                'files.*.required' => 'Ce champ est Obligatoire',
                'files.*.file' => 'Seuls les fichiers images et PDF sont autorisés',
            ]

        );
        if ($validator->fails()) {
            return Redirect::back()->withErrors($validator->messages());
        }
        $dossier = Dossier::whereId($request->dossier_id)->with('step', 'company', 'typeexpertise', 'guarantee', 'devis')->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 (!$dossier->vehiculemodel) {
            return redirect()->back()->with('error', 'Svp de Ajouter Modele du Vehicule ');
        }
        if (!$dossier->typeexpertise) {
            return redirect()->back()->with('error', 'Svp de Ajouter Type Expertise Avant la Creation du Devis ');
        }
        if (!$dossier->guarantee) {
            return redirect()->back()->with('error', 'Svp de Ajouter Garantie Avant la Creation du Devis ');
        }
        $doc = Document::where('dossier_id', $dossier->id)->where('type_document_id', 5)->count();

        if ($dossier->mode_id == 2 || $dossier->mode_id == 3) {
            if (!$dossier->valeurneuf) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur A Neuf');
            }
            if (!$dossier->valeuradire) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur A Dire');
            }
            if (!$dossier->horssinistre) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur Hors Sinistre');
            }
            if (!$dossier->valeurepave) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur Epavee');
            }
            if (!$dossier->valeurvenale) {
                return redirect()->back()->with('error', 'Svp de Saisir Valeur Venale');
            }
        }
        $devis = Devis::where('dossier_id', $dossier->id)->latest()->first();
        $chiffreur = User::where('role_id', 2)->withCount('step')
            ->whereHas('typecompany', function ($query) use ($dossier) {
                $query->where('company_id', $dossier->company_id)->where('type_expertise_id', $dossier->type_expertise_id);
            })
            ->whereHas('seuil', function ($query) use ($request, $dossier) {
                $query->where('max', '>=', $request->montant_devis)->where('min', '<=', $request->montant_devis)->where('company_id', $dossier->company_id);
            })->orderBy('step_count', 'asc')
            ->first();

        if (!$chiffreur) {
            $chiffreur = User::where('role_id', 4)->first();
        }

        // if ($devis) {
        //     if ($devis->devis_status_id == 4) {
        //         return redirect()->back()->with('error', 'Svp de Traiter devis encours');
        //     }
        // }
        // upload files normal
        $type = TypeDocument::whereId(4)->firstOrFail();
        if ($doc > 0) {
            $status = DevisStatus::whereId(4)->first();
        } else {
            $status = DevisStatus::whereId(9)->first();
        }
        if ($request->file('files')) {
            $deviscount = Devis::where('dossier_id', $dossier->id)->count();
            $numdevis = $deviscount + 1;
            if ($deviscount > 0) {
                $olddevis = Devis::where('dossier_id', $request->dossier_id)->with('piece')->latest()->first();
                if ($olddevis->devis_status_id == 4 || $olddevis->devis_status_id == 9) {
                    return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Devis deja en cours');
                }
            }
            $devis = Devis::create([
                'montant_devis' => $request->montant_devis,
                'dossier_id' => $request->dossier_id,
                'devis_status_id' => $status->id,
                'ref' => $request->ref,
                'date_reception' => $request->date,
                'devis' => $numdevis
            ]);
            $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
            if ($deviscount > 0) {
                $devis->taux_id = $olddevis->taux_id;
                $devis->update();
                foreach ($olddevis->piece as $p) {
                    $devis->piece()->attach($p, [
                        'qte' => $p->pivot->qte,
                        'prix_unitaire' => $p->pivot->prix_unitaire,
                        'gravite' => $p->pivot->gravite,
                        'etat' => $p->pivot->etat,
                        'vetuste' => $p->pivot->vetuste ?? 0,
                        'remise' => $p->pivot->remise ?? 0,
                        'montant_ht' => $p->pivot->montant_ht,
                        'type_reparation_id' => $p->pivot->type_reparation_id,
                        'operation_id' => $p->pivot->operation_id,
                        'vehicule_model_id' => $dossier->vehicule_model_id
                    ]);
                }
            }


            $files = $request->file('files');
            //convert pdf to image and store the images
            if (isset($request->pdfs)) {

                $array = explode(",", $request->pdfs);
                for ($i = 1; $i < count($array); $i += 2) {
                    $image = base64_decode($array[$i]);
                    $filename = uniqid() . '.' . 'png';
                    Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $image);
                    $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                    $d = Document::create([
                        'path' => $path,
                        'dossier_id' => $dossier->id,
                        'type_document_id' => $type->id
                    ]);
                    $devis->document()->attach($d->id);
                }
            }
            $files = $request->file('files');
            foreach ($files as $file) {
$pdfMimes = ['application/pdf', 'application/x-pdf', 'application/acrobat', 'application/vnd.pdf', 'text/pdf', 'text/x-pdf'];
                $isPdf = in_array($file->getMimeType(), $pdfMimes) || strtolower($file->getClientOriginalExtension()) == 'pdf';
                
                if ($isPdf) {
                    // Convert PDF to images using Imagick
                    $tempDir = storage_path('app/temp/pdf_' . uniqid());
                    if (!file_exists($tempDir)) {
                        mkdir($tempDir, 0755, true);
                    }
                    
                    $tempPdfPath = $tempDir . '/' . uniqid() . '.pdf';
                    copy($file->getRealPath(), $tempPdfPath);
                    
                    if (extension_loaded('imagick')) {
                        $imagick = new \Imagick();
                        $imagick->setResolution(150, 150);
                        $imagick->readImage($tempPdfPath);
                        $pageCount = $imagick->getNumberImages();
                        
                        for ($i = 0; $i < $pageCount; $i++) {
                            $imagick->setIteratorIndex($i);
                            $imagick->setImageFormat('png');
                            $imagick->setImageCompressionQuality(90);
                            $imagick->setImageBackgroundColor('white');
                            $imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
                            
                            $tempImagePath = $tempDir . '/' . uniqid() . '.png';
                            $imagick->writeImage($tempImagePath);
                            
                            $filename = uniqid() . '.png';
                            $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                            Storage::disk('s3')->put($path3, file_get_contents($tempImagePath));
                            $docs = Document::create([
                                'path' => $path3,
                                'type_document_id' => $type->id,
                                'dossier_id' => $dossier->id,
                            ]);
                            $devis->document()->attach($docs->id);
                            unlink($tempImagePath);
                        }
                        $imagick->clear();
                        $imagick->destroy();
                    }
                    
                    unlink($tempPdfPath);
                    rmdir($tempDir);
                } else {
                    $filename = uniqid() . '.' . File::extension($file->getClientOriginalName());
                    $path3 = $file->storeAs('documents/' . $dossier->ref . '/' . $type->type, $filename, 's3');
                    // Store the file in the disk
                    $docs = Document::create([
                        'path' => $path3,
                        'type_document_id' => $type->id,
                        'dossier_id' => $dossier->id,
                    ]);
                    $devis->document()->attach($docs->id);
                }
            }
            Montant::updateOrCreate(['dossier_id' => $dossier->id], [
                'devis_id' => $devis->id,
            ]);

            if ($devis->devis == 2) {
                $step = Step::whereId(18)->first();
            } elseif ($devis->devis == 3) {
                $step = Step::whereId(21)->first();
            } else {
                $step = Step::whereId(3)->first();
            }

            if (Auth::check()) {
                $dossier->step()->attach($step, ['user_id' => Auth::user()->id]);
            }
            $dossier->step_id = $step->id;
            $dossier->update();
            if ($devis->devis == 2) {
                $step = Step::whereId(19)->first();
            } elseif ($devis->devis == 3) {
                $step = Step::whereId(22)->first();
            } else {
                $step = Step::whereId(4)->first();
            }
            $dossier->step()->attach($step, ['user_id' => $chiffreur->id]);
            $dossier->step_id = $step->id;
            $dossier->update();
            $body = "Un Nouveau Devis est Créer  " . $devis->dossier->ref . " et Affecter a " . $chiffreur->name;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $devis->dossier->id,
                'body' => $body
            ]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('home')->with('success', $body);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Devis  $devis
     * @return \Illuminate\Http\Response
     */
    public function show($id, Request $request)
    {
        $this->authorize('view', Devis::class);

        $user = User::whereId(Auth::user()->id)->first();
        $devis = Devis::whereId($id)->with('dossier', 'devisstatus', 'piece.piecetype', 'taux')->firstOrFail();
        $dossier = Dossier::whereId($devis->dossier_id)->with('document', 'currency', 'document.typedocument')
            ->with('document', function ($query) {
                $query->whereHas('typedocument', function ($query) {
                    $query->where('is_pdf', 0);
                });
            })->firstOrFail();
        $historiques = Dossier::where('id', '!=', $dossier->id)->where('dossier_status_id', 2)
            ->where(function ($query) use ($dossier) {
                if (!empty($dossier->matricule)) {
                    $query->where('matricule', $dossier->matricule);
                }
                if (!empty($dossier->new_matricule)) {
                    $query->orWhere('new_matricule', $dossier->new_matricule);
                }
            })
            ->count();
        // dd($devis->piece);

        if (!$dossier->vehiculemodel) {
            return redirect()->back()->with('error', 'Ajouter Modéle du Vehicule Au dossier ');
        }
        if (!$dossier->guarantee) {
            return redirect()->back()->with('error', 'Ajouter Garantie Au dossier ');
        }

        $montant = Montant::where('dossier_id', $dossier->id)->first();
        if ($montant) {
        } else {
            Montant::updateOrCreate(['dossier_id' => $dossier->id], [
                'devis_id' => $devis->id,
            ]);
        }

        $docdevis = Document::where('dossier_id', $devis->dossier->id)->with('typedocument', 'devis')->where('type_document_id', 4)->latest()->get();
        $observations = Observation::where('dossier_id', $devis->dossier_id)->get();
        $typedocuments = TypeDocument::where('is_pdf', '0')->whereHas('document', function ($query) use ($dossier) {
            $query->where('dossier_id', $dossier->id);
        })->get();

        if ($request->doc_id) {
            $document = Document::whereId($request->doc_id)->where('dossier_id', $dossier->id)->whereIn('type_document_id', [4, 29])->first();
        } else {
            $document = Document::where('dossier_id', $dossier->id)->where('type_document_id', 4)->latest()->first();
        }

        $imagePath = Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30));
        // $image = Image::make($imagePath);
        // $image->resize(750, 850);

        // // Get the width and height of the image
        // $document->width = $image->width();
        // $document->height = $image->height();

        $types = TypeReparation::all();
        $typeingredients = TypeIngredient::all();
        $operations = Operation::all();
        $piecetypes = PieceType::where('svg', 1)->get();
        $modes = Mode::all();

        $array = [];
        if ($devis->piece) {
            foreach ($devis->piece as $p) {
                array_push($array, $p->id);
            }
        }
        // $pieces = Piece::where('vehicule_model_id', $dossier->vehicule_model_id)->whereHas('rapport')->whereNotIn('id', $array)->with('piecetype', 'operation', 'typereparation', 'rapport')->get();

        return view('devis.show', compact('typedocuments', 'historiques', 'piecetypes', 'document', 'observations', 'montant', 'modes', 'devis', 'docdevis', 'dossier', 'types', 'typeingredients', 'operations', 'user'));
    }

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

        $devis = Devis::whereId($id)->with('dossier', 'document')->first();
        $count = 0;
        foreach ($devis->document as $d) {
            if ($d->edited == 1) {
                $count++;
            }
        }
        $dossier = Dossier::whereId($devis->dossier_id)->with('montant')->firstOrFail();
        $traitstep = Step::whereId(4)->first();
        $dossier->step()->attach($traitstep, ['user_id' => Auth::user()->id]);


        if ($request->input('action') != "rejeter" && $request->input('action') != 'retraiter') {
            if ($dossier->type_expertise_id == 4 || $dossier->type_expertise_id == 3 || $dossier->type_expertise_id == 5 || $dossier->type_expertise_id == 6 || $dossier->type_expertise_id == 7) {
            } else {

                if ($dossier->mode_id == 2 || $dossier->mode_id == 3) {
                    if (!$dossier->valeuradire) {
                        return redirect()->back()->with('error', 'Merci de saisir les valeurs');
                    }
                } else {
                    // dd(1);
                    $request->validate([
                        'montant_accord' => 'required|numeric'
                    ]);
                }

                $montant = Montant::where('dossier_id', $devis->dossier_id)->first();
                $montant->montant_accord = $request->montant_accord;
                $montant->update();
            }
        }

        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($devis->devis_status_id == 8 ){


        // } else{
        // }
        $seuil = Seuil::where('company_id', $dossier->company_id)->where('user_id', Auth::user()->id)->first();

        if (!$seuil) {
            if ($devis->devis_status_id == 8) {
                $seuil = Seuil::where('user_id', Auth::user()->id)
                    ->orderBy('accord', 'desc') // Order by 'accord' in descending order
                    ->first();
            }
        }

        $user = User::whereId(Auth::user()->id)->first();
        if ($devis->devis == 2) {
            $step = Step::whereId(20)->first();
        } elseif ($devis->devis == 2) {
            $step = Step::whereId(23)->first();
        } else {
            $step = Step::whereId(5)->first();
        }
        if ($request->input('action') == "accord") {
            if ($dossier->sinistre_douteux) {
                $document = Document::where('type_document_id', 14)->count();
                if ($document == 0) {
                    return redirect()->back()->with('error', 'Merci de Créer un Rapport Technique');
                }
            }

            if (($dossier->mode_id != 2 && $dossier->mode_id != 3) && ($dossier->type_expertise_id == 4 || $dossier->type_expertise_id == 3 || $dossier->type_expertise_id == 5 || $dossier->type_expertise_id == 6 || $dossier->type_expertise_id == 7)) {
                $i = 0;
                $tva = 0;
                $tvaa2 = 0;
                $montantpieces = 0;
                $vet = 0;
                $mo = 0;
                foreach ($devis->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 {
                        $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;

                        // $montantpieces = $montantpieces - ($piece->pivot->qte * $piece->pivot->prix_unitaire * $piece->pivot->remise / 100);
                        $tvaa2 += $tvaa;
                        if ($devis->taux) {
                            if ($devis->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);
                        }
                    }
                    $i++;
                }

                if ($i == 0) {
                    return redirect()->back()->with('error', 'Merci de Ajouter les Pieces');
                }
                if ($devis->taux) {
                    $remisep = ($devis->taux->taux_mo_peinture * $devis->taux->tp * $devis->taux->remise_sur_total_mo_peinture) / 100;
                    $montantpieces = $montantpieces - $remisep;

                    if ($devis->taux->taux_ing) {
                        $taux_ing_metal = $devis->taux->taux_ing_metal + $devis->taux->taux_ing_metal * 0.2;
                        $taux_ing_metal_vernis = $devis->taux->taux_ing_metal_vernis + $devis->taux->taux_ing_metal_vernis * 0.2;
                        $taux_ing_nacre_vernis = $devis->taux->taux_ing_nacre_vernis + $devis->taux->taux_ing_nacre_vernis * 0.2;
                        $taux_ing_opaque = $devis->taux->taux_ing_opaque + $devis->taux->taux_ing_opaque * 0.2;
                        $taux_ing_opaque_vernis = $devis->taux->taux_ing_opaque_vernis + $devis->taux->taux_ing_opaque_vernis * 0.2;
                        $tva = $tvaa2 + $devis->taux->taux_ing_opaque_vernis * 0.2 + $devis->taux->taux_ing_opaque * 0.2 + $devis->taux->taux_ing_nacre_vernis * 0.2 + $devis->taux->taux_ing_metal_vernis * 0.2 + $devis->taux->taux_ing_metal * 0.2;
                    } else {
                        $taux_ing_metal = $devis->taux->taux_ing_metal;
                        $taux_ing_metal_vernis = $devis->taux->taux_ing_metal_vernis;
                        $taux_ing_nacre_vernis = $devis->taux->taux_ing_nacre_vernis;
                        $taux_ing_opaque = $devis->taux->taux_ing_opaque;
                        $taux_ing_opaque_vernis = $devis->taux->taux_ing_opaque_vernis;
                        $tva = $tva + $tvaa2;
                    }
                    if ($devis->taux->taux_tva) {
                        $main01 = $devis->taux->taux_1 * $devis->taux->t1 + $devis->taux->taux_1 * $devis->taux->t1 * 0.2;
                        $main02 = $devis->taux->taux_2 * $devis->taux->t2 + $devis->taux->taux_2 * $devis->taux->t2 * 0.2;
                        $main03 = $devis->taux->taux_3 * $devis->taux->t3 + $devis->taux->taux_3 * $devis->taux->t3 * 0.2;
                        $main04 = $devis->taux->taux_mo_peinture * $devis->taux->tp + $devis->taux->taux_mo_peinture * $devis->taux->tp * 0.2;
                        $main05 = $devis->taux->taux_electricite * $devis->taux->te + $devis->taux->taux_electricite * $devis->taux->te * 0.2;
                        $main06 = $devis->taux->taux_controle * $devis->taux->tc + $devis->taux->taux_controle * $devis->taux->tc * 0.2;
                        $main07 = $devis->taux->taux_mecanique * $devis->taux->tm + $devis->taux->taux_mecanique * $devis->taux->tm * 0.2;
                        $tva += $devis->taux->taux_mecanique * $devis->taux->tm * 0.2 + $devis->taux->taux_controle * $devis->taux->tc * 0.2 + $devis->taux->taux_electricite * $devis->taux->te * 0.2 + $devis->taux->taux_mo_peinture * $devis->taux->tp * 0.2 + $devis->taux->taux_3 * $devis->taux->t3 * 0.2 + $devis->taux->taux_2 * $devis->taux->t2 * 0.2 + $devis->taux->taux_1 * $devis->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 = $devis->taux->remise_facture + ($sum * ($devis->taux->remise_facture1 / 100));
                        $fr = $devis->taux->franchise + (($sum) * ($devis->taux->franchise_fix / 100));
                        $ttl = $sum;
                    } else {
                        $main01 = $devis->taux->taux_1 * $devis->taux->t1;
                        $main02 = $devis->taux->taux_2 * $devis->taux->t2;
                        $main03 = $devis->taux->taux_3 * $devis->taux->t3;
                        $main04 = $devis->taux->taux_mo_peinture * $devis->taux->tp;
                        $main05 = $devis->taux->taux_electricite * $devis->taux->te;
                        $main06 = $devis->taux->taux_controle * $devis->taux->tc;
                        $main07 = $devis->taux->taux_mecanique * $devis->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 = $devis->taux->remise_facture + ($sum * ($devis->taux->remise_facture1 / 100));
                        $fr = $devis->taux->franchise + (($sum) * ($devis->taux->franchise_fix / 100));
                        $ttl = $sum;
                    }
                    $montant = Montant::where('dossier_id', $devis->dossier_id)->first();
                    $montant->montant_accord = $ttl;
                    $montant->update();
                } else {
                    return redirect()->back()->with('error', 'Merci de Ajouter Taux');
                }
            } else {
                if ($dossier->mode_id == 2 || $dossier->mode_id == 3) {
                    if (!$dossier->valeuradire) {
                        return redirect()->back()->with('error', 'Merci de saisir les valeurs');
                    }
                } else {

                    $request->validate([
                        'montant_accord' => 'required|numeric'
                    ]);
                }

                $montant = Montant::where('dossier_id', $devis->dossier_id)->first();
                $montant->montant_accord = $request->montant_accord;
                $montant->update();
            }

            if (Auth::user()->role_id === 4) {
                $status = DevisStatus::whereId(2)->first();
                $now = now();

                if ($devis->devis_status_id === 8) {
                    $chif = DB::table('devis_status')->where('devis_id', $devis->id)->where('devis_status_id', 8)->latest()->first();
                    $controled = User::whereId($chif->user_id)->first();
                    $dossier->step()->attach($step, ['user_id' => $controled->id]);
                    $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                    $text = $dossier->ref . " : Devis Accord par  " . $controled->name;
                } else {
                    $text = $dossier->ref . " : Devis Accord par  " . Auth::user()->name . " le " . $now;
                    $dossier->step()->attach($step, ['user_id' => $user->id]);
                    $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                }

                $devis->devis_status_id = 2;
                $devis->update();
                $body = "Accord Devis:" . $devis->dossier->ref;
                Notification::create([
                    'user_id' => Auth::user()->id,
                    'dossier_id' => $devis->dossier->id,
                    'body' => $text
                ]);
                $dossier->step_id = $step->id;
                $dossier->update();

                foreach ($devis->document as $doc) {
                    if ($count == 0) {
                        $imageContent = Storage::disk('s3')->get($doc->path);
                        $img = Image::make($imageContent);
                        $watermarkWidth = $img->width() * 15 / 100;
                        $watermarkHeight = $img->height() * 15 / 100;
                        $watermark = Image::make(public_path('/img/amea2.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);
                        $watermark2 = Image::make(public_path('/img/sign.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);
                        $img->insert($watermark, 'top-left', 10, 10);
                        $img->insert($watermark2, 'bottom-right', 10, 10);

                        $img->text($text, 80, 30, function ($font) {
                            $font->file(public_path('fonts/gnuolane.ttf'));
                            $font->size(17);
                            $font->color('#000000');
                            $font->align('bottom');
                            $font->valign('right');
                            $font->angle(0);
                        });
                        $type = TypeDocument::whereId(29)->first();
                        $filename = uniqid() . '.' . 'png';
                        Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                        $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                        // Store the file in the disk
                        $docu = Document::create([
                            'path' => $path3,
                            'type_document_id' => $type->id,
                            'dossier_id' => $dossier->id,
                        ]);
                        $devis->document()->attach($docu->id);
                    } else {
                        if ($doc->edited == 1) {
                            $imageContent = Storage::disk('s3')->get($doc->path);
                            $img = Image::make($imageContent);
                            $watermarkWidth = $img->width() * 15 / 100;
                            $watermarkHeight = $img->height() * 15 / 100;
                            $watermark = Image::make(public_path('/img/amea2.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);
                            $watermark2 = Image::make(public_path('/img/sign.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);

                            $img->insert($watermark, 'top-left', 10, 10);
                            $img->insert($watermark2, 'bottom-right', 10, 10);

                            $img->text($text, 80, 30, function ($font) {
                                $font->file(public_path('fonts/gnuolane.ttf'));
                                $font->size(16);
                                $font->color('#000000');
                                $font->align('bottom');
                                $font->valign('right');
                                $font->angle(0);
                            });
                            $type = TypeDocument::whereId(29)->first();
                            $filename = uniqid() . '.' . 'png';
                            Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                            $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                            // Store the file in the disk
                            $docu = Document::create([
                                'path' => $path3,
                                'type_document_id' => $type->id,
                                'dossier_id' => $dossier->id,
                            ]);
                            $devis->document()->attach($docu->id);
                        }
                    }
                }
                return redirect()->route('home')->with('success', 'Devis Accord ');
            }
            $dossierr = Dossier::whereId($devis->dossier_id)->with('montant')->firstOrFail();

            // if(Gate::allows('chiffrage', $devis)){}
            if ($seuil) {

                if ($user->controler == 1 || intval($dossierr->montant->montant_accord) > intval($seuil->accord)) {
                    $devis->devis_status_id = 8;
                    $devis->update();
                    $status = DevisStatus::whereId(8)->first();
                    $dossier->step()->attach($step, ['user_id' => $user->id]);
                    $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                    $body = "Merci de Controller Devis :" . $devis->dossier->ref;
                    Notification::create([
                        'user_id' => Auth::user()->id,
                        'dossier_id' => $devis->dossier->id,
                        'body' => $body
                    ]);

                    return redirect()->route('home')->with('success', 'Accord devis sera Valider par Expert');
                } else {
                    $devis->devis_status_id = 2;
                    $devis->update();
                    $dossier->step_id = $step->id;
                    $dossier->update();
                    $now = now();
                    $text = $dossier->ref . " : Devis Accord par  " . Auth::user()->name . " le " . $now;
                    $dossier->step()->attach($step, ['user_id' => $user->id]);
                    $status = DevisStatus::whereId(2)->first();
                    $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                    foreach ($devis->document as $doc) {
                        if ($count == 0) {
                            $imageContent = Storage::disk('s3')->get($doc->path);
                            $img = Image::make($imageContent);
                            $watermarkWidth = $img->width() * 15 / 100;
                            $watermarkHeight = $img->height() * 15 / 100;
                            $watermark = Image::make(public_path('/img/amea2.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);
                            $watermark2 = Image::make(public_path('/img/sign.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);

                            $img->insert($watermark, 'top-left', 10, 10);
                            $img->insert($watermark2, 'bottom-right', 10, 10);

                            $img->text($text, 80, 30, function ($font) {
                                $font->file(public_path('fonts/gnuolane.ttf'));
                                $font->size(17);
                                $font->color('#000000');
                                $font->align('bottom');
                                $font->valign('right');
                                $font->angle(0);
                            });
                            $type = TypeDocument::whereId(29)->first();
                            $filename = uniqid() . '.' . 'png';
                            Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                            $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                            // Store the file in the disk
                            $docu = Document::create([
                                'path' => $path3,
                                'type_document_id' => $type->id,
                                'dossier_id' => $dossier->id,
                            ]);
                            $devis->document()->attach($docu->id);
                        } else {
                            if ($doc->edited == 1) {
                                $imageContent = Storage::disk('s3')->get($doc->path);
                                $img = Image::make($imageContent);
                                $watermarkWidth = $img->width() * 15 / 100;
                                $watermarkHeight = $img->height() * 15 / 100;
                                $watermark = Image::make(public_path('/img/amea2.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);
                                $watermark2 = Image::make(public_path('/img/sign.png'))->resize($watermarkHeight, $watermarkWidth)->opacity(70);

                                $img->insert($watermark, 'top-left', 10, 10);
                                $img->insert($watermark2, 'bottom-right', 10, 10);

                                $img->text($text, 80, 30, function ($font) {
                                    $font->file(public_path('fonts/gnuolane.ttf'));
                                    $font->size(16);
                                    $font->color('#000000');
                                    $font->align('bottom');
                                    $font->valign('right');
                                    $font->angle(0);
                                });
                                $type = TypeDocument::whereId(29)->first();
                                $filename = uniqid() . '.' . 'png';
                                Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                                $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                                // Store the file in the disk
                                $docu = Document::create([
                                    'path' => $path3,
                                    'type_document_id' => $type->id,
                                    'dossier_id' => $dossier->id,
                                ]);
                                $devis->document()->attach($docu->id);
                            }
                        }
                    }
                    $body = " Devis Accord :" . $devis->dossier->ref;
                    Notification::create([
                        'user_id' => Auth::user()->id,
                        'dossier_id' => $devis->dossier->id,
                        'body' => $body
                    ]);
                    \App\Services\SidebarCache::clear();

                    return redirect()->route('home')->with('success', 'Devis Accord ');
                }
            } else {
                return redirect()->route('Dossier.show', $devis->dossier_id)->with('error', 'Demander a Admin de vous ajouter un Seuil');
            }
        } else
            if ($request->input('action') == "rejeter") {
                $request->validate([
                    'observation' => 'required',
                ]);
                $body = " Devis Rejeter :" . $devis->dossier->ref;
                Notification::create([
                    'user_id' => Auth::user()->id,
                    'dossier_id' => $devis->dossier->id,
                    'body' => $body
                ]);
                Observation::create([
                    'observation' => $request->observation,
                    'dossier_id' => $devis->dossier_id,
                    'user_id' => Auth::user()->id
                ]);

                $devis->devis_status_id = 1;
                $devis->update();
                if ($devis->devis == 2) {
                    $oldstep = Step::whereId(18)->first();
                } elseif ($devis->devis == 3) {
                    $oldstep = Step::whereId(21)->first();
                } else {
                    $oldstep = Step::whereId(3)->first();
                }
                $stepuser = DB::table('step_dossier')
                    ->where('dossier_id', $dossier->id)
                    ->where('step_id', 1)
                    ->latest()->first();
                $dossier->step_id = $oldstep->id;
                $dossier->update();
                $dossier->step()->attach($oldstep, ['user_id' => $stepuser->user_id]);

                $status = DevisStatus::whereId(1)->first();
                $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                \App\Services\SidebarCache::clear();
                return redirect()->route('home')->with('success', 'Devis Rejeter');
            }
        if ($request->input('action') == "avis") {
            $request->validate([
                'observation' => 'required',
            ]);

            Observation::create([
                'observation' => $request->observation,
                'dossier_id' => $devis->dossier_id,
                'user_id' => Auth::user()->id
            ]);
            $devis->devis_status_id = 3;
            $devis->update();
            $body = "Demande Avis Devis :" . $devis->dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $devis->dossier->id,
                'body' => $body
            ]);
            $status = DevisStatus::whereId(3)->first();
            $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('home')->with('success', 'Devis Demander Avis');

            // $dossier->step()->attach($step2, ['user_id', $user->id]);
        }
        if ($request->input('action') == 'retraiter') {
            $request->validate([
                'observation' => 'required',
            ]);
            Observation::create([
                'observation' => $request->observation,
                'dossier_id' => $devis->dossier_id,
                'user_id' => Auth::user()->id
            ]);
            $devis->devis_status_id = 5;
            $devis->update();

            foreach ($devis->document as $doc) {
                $doc->edited = 0;
                $doc->update();
            }
            $body = " Devis a Retraiter :" . $devis->dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $devis->dossier->id,
                'body' => $body
            ]);
            $status = DevisStatus::whereId(5)->first();
            $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('home')->with('success', 'Devis a Retraiter');
        }

        if ($request->input('action') == 'envoyer') {

            if ($devis->devis_status_id == 2) {
                $devis->devis_status_id = 7;
                $devis->update();
                $body = " Devis Envoyer :" . $devis->dossier->ref;
                Notification::create([
                    'user_id' => Auth::user()->id,
                    'dossier_id' => $devis->dossier->id,
                    'body' => $body
                ]);
                $status = DevisStatus::whereId(7)->first();
                $devis->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                \App\Services\SidebarCache::clear();
                return redirect()->route('home')->with('success', 'Devis Envoyer');
            }
        }

        return redirect()->back();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Devis  $devis
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $devis = Devis::whereId($id)->firstOrFail();

        $dossier = Dossier::whereId($devis->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 ');
        }

        // $step = DB::table('step_dossier')
        //     ->where('dossier_id', $dossier->id)
        //     ->latest()->first();
        // if (Auth::user()->id != $step->user_id) {
        //     return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Vous avez pas le droit de apporter des modification a ce dossier maintenant');
        // }
        $request->validate([
            'montant_devis' => 'required|numeric',
            'montant_accord' => 'nullable|numeric',
            'montant_facture' => 'nullable|numeric',
            'montant_rapport' => 'nullable|numeric'
        ]);

        $devis->montant_devis = $request->montant_devis;
        $devis->montant_accord = $request->montant_accord;
        $devis->montant_rapport = $request->montant_rapport;
        $devis->montant_facture = $request->montant_facture;
        $devis->update();
        \App\Services\SidebarCache::clear();
        return redirect()->back();
    }

    public function attach(Request $request)
    {
        try {

            $devis = Devis::whereId($request->devis_id)->with('piece', 'dossier')->first();
            $devis->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 ($devis->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;

                    $devis->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' => $devis->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 updatedossier($id, Request $request)
    {

        $dossier = Dossier::whereId($id)->firstOrFail();
        $request->validate([
            'mode_id' => 'exists:mode,id'
        ]);

        $dossier->mode_id = $request->mode;
        $dossier->horssinistre = $request->horssinistre;
        $dossier->valeurepave = $request->valeurepave;
        $dossier->valeurneuf = $request->valeurneuf;
        $dossier->valeurvenale = $request->valeurvenale - $request->horssinistre;
        $dossier->valeuradire = ($request->valeurvenale - $request->valeurepave - $request->horssinistre);
        $dossier->horssinistre_ttc = $request->horssinistre_ttc;
        $dossier->valeurepave_ttc = $request->valeurepave_ttc;
        $dossier->valeurneuf_ttc = $request->valeurneuf_ttc;
        $dossier->valeurvenale_ttc = $request->valeurvenale_ttc - $request->horssinistre_ttc;
        $dossier->valeuradire_ttc = ($request->valeurvenale_ttc - $request->valeurepave_ttc - $request->horssinistre_ttc);
        $dossier->update();

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

    public function destroy($id)
    {
        if (Auth::user()->role_id == 4) {
            $devis = Devis::whereId($id)->firstOrFail();
            if ($devis->devis_status_id == 4 || $devis->devis_status_id == 9) {
                $docdevis = DB::table('document_devis')->where('devis_id', $devis->id)->get();
                DB::table('devis_status')->where('devis_id', $devis->id)->delete();
                DB::table('document_devis')->where('devis_id', $devis->id)->delete();
                foreach ($docdevis as $d) {
                    $doc = Document::whereId($d->document_id)->first();
                    $doc->delete();
                }
                DB::table('devis_piece')->where('devis_id', $devis->id)->delete();
                $montant = Montant::where('dossier_id', $devis->dossier_id)->first();
                $montant->devis_id = null;
                $montant->update();
                $devis->delete();
                \App\Services\SidebarCache::clear();
                return redirect()->back()->with('success', 'Devis Supprimer Avec Succés');
            } else {
                return redirect()->back()->with('error', 'Devis est deja en traitement');
            }
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Devis  $devis
     * @return \Illuminate\Http\Response
     */
    // public function devispiece(Request $request ,$id)
    // {
    //     $devis = Devis::whereId($request->devis_id)->first();
    //     $piece = Piece::whereId($id)->first();
    //     $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, 'vetuste' => $request->vetuste, 'remise' => $request->remise, 'montant_ht' => $montant]);
    //     return redirect()->back()->with('success','Piece Ajouter avec Succés');
    // }


}
