<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\NoteHonoraire;
use App\Models\Payment;
use App\Models\Settlement;
use App\Models\TypeDocument;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Sabberworm\CSS\Settings;

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

        $companies = Company::all();
        return view('configuration.settlement.index', compact('companies'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create', Settlement::class);

        $companies = Company::all();
        $settlement = Settlement::latest()->first();
        return view('configuration.settlement.create', compact('companies'));
    }

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

        $request->validate([
            'numero_facture' => 'required',
            'montant' => 'required|numeric|min:1',
            'banque' => 'required',
            'mode_paiement' => 'required',
            'date_facture' => 'required',
            'company_id' => 'required'
        ]);

        $settlement = Settlement::where('company_id',$request->company_id)->latest()->first();

        if ($settlement) {
            if ($settlement->reste == 0) {

                $set = Settlement::create([
                    'numero_facture' => $request->numero_facture,
                    'montant' => $request->montant,
                    'banque' => $request->banque,
                    'mode_paiement' => $request->mode_paiement,
                    'date_facture' => $request->date_facture,
                    'company_id' => $request->company_id,
                    'reste' => $request->montant,
                    'date_paiement' => Carbon::today()
                ]);
                return redirect()->route('Settlement.show',$set->company_id)->with('success', 'Success');
            } else {
                return redirect()->back()->with('error', 'Il Faut terminer Avant d ajouter Un nouveau');
            }
        } else {
            $set = Settlement::create([
                'numero_facture' => $request->numero_facture,
                'montant' => $request->montant,
                'banque' => $request->banque,
                'mode_paiement' => $request->mode_paiement,
                'date_facture' => $request->date_facture,
                'company_id' => $request->company_id,
                'reste' => $request->montant,
                'date_paiement' => Carbon::today()
            ]);
            return redirect()->route('Settlement.show',$set->company_id)->with('success', 'Success');

        }

        return redirect()->route('Settlement.index');
    }

    public function all()
    {
        $this->authorize('viewAny', Settlement::class);

        $settlements = Settlement::latest()->paginate(10);
        return view('configuration.settlement.all', compact('settlements'));
    }

    public function get($id)
    {
        $this->authorize('view', Settlement::class);
        $settlement = Settlement::whereId($id)->with('payment')->first();
        $payments = Payment::with('dossier')->whereHas('settlement',function($query) use ($id) {
            $query->where('settlement_id',$id);
        })->get();
        return view('configuration.settlement.details', compact('settlement','payments'));
    }

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

        $company = Company::whereId($id)->firstOrFail();
        $payments = Payment::with('notehonoraire', 'dossier')->where('note_honoraire_status_id', 2)->whereHas('notehonoraire', function ($query) use ($id) {
            $query->where('company_id', $id);
        })->get();
        $balance = Settlement::where('company_id', $company->id)->sum('reste');
        $montant = Payment::where('note_honoraire_status_id', 2)->whereHas('dossier', function($query) use ($id){
            $query->where('company_id',$id);
        })->sum('montant_restant');

        return view('configuration.settlement.show', compact('payments', 'balance', 'company', 'montant'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Settlement  $settlement
     * @return \Illuminate\Http\Response
     */
    public function search(Request $request)
    {
        $this->authorize('view', Settlement::class);
        if(!$request->search){
            return redirect()->route('Settlement.show',$request->company);
        }
        $payments = Payment::where('ref',$request->search)->whereHas('notehonoraire', function ($query) use ($request) {
            $query->where('company_id', $request->company);
        })->get();
        $balance = Settlement::where('company_id', $request->company)->sum('reste');
        $montant = Payment::where('note_honoraire_status_id', 2)->sum('montant_restant');
        $company = Company::whereId($request->company)->firstOrFail();

        return view('configuration.settlement.show', compact('payments', 'montant', 'company', 'balance'));
    }

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


        $payment = Payment::whereId($id)->with('dossier')->firstOrFail();
        $dossier = Dossier::whereId($payment->dossier_id)->firstOrFail();
        $settlement = Settlement::where('company_id', $payment->dossier->company_id)->latest()->first();
        $note = NoteHonoraire::whereId($payment->note_honoraire_id)->firstOrFail();
        $ht = $payment->frais_deplacement + $payment->frais_sejour + $payment->frais_divers + $payment->notehonoraire->montant;
        $tva = $ht / 20;
        $ttc = $ht - $tva;
        if ($settlement->reste >= $payment->montant_restant) {

            $settlement->reste = $settlement->reste - $payment->montant_restant;
            $settlement->update();
            $payment->montant_restant = 0;
            $payment->note_honoraire_status_id = 1;
            $payment->update();
            $payment->settlement()->attach($settlement);
            $type = TypeDocument::whereId(12)->first();
            $pdf = PDF::loadView('configuration.pdf.noteHonoraire', compact('dossier', 'note', 'payment', 'ttc', 'ht', 'tva'));
            $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,
            ]);

        } else {

            $payment->montant_restant = $payment->montant_restant - $settlement->reste;
            $payment->update();
            $settlement->reste = 0;
            $settlement->update();
            $payment->settlement()->attach($settlement);
        }
        // dd($payment);

        return redirect()->route('Settlement.show',$settlement->company_id)->with('success', 'payer avec succés');
        // } else {
        //     return redirect()->back()->with('error', 'Vous Navez Pas assez de Solde ');
        // }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Settlement  $settlement
     * @return \Illuminate\Http\Response
     */
    public function destroy(Settlement $settlement)
    {
        //
    }
}
