<?php

namespace App\Http\Controllers;

use App\Models\Billet;
use App\Models\Chauffeur;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Storage;
use PDF;




use Illuminate\Support\Facades\Mail;
use App\Mail\BilletPdfEmail;


class BilletController extends Controller
{


  

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $billets = Billet::latest()->paginate(5);
        $chauffeurs = Chauffeur::all();

        return view('billets.index', compact('billets'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $chauffeurs = Chauffeur::all();

        return view('billets.create', compact('chauffeurs'));


    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'vehicule' => 'nullable|string',
            'chauffeur1' => 'nullable|string',
            'telephone1' => 'nullable|string',
            'chauffeur2' => 'nullable|string',
            'telephone2' => 'nullable|string',
            'adresseclient' => 'nullable|string',  // Corrected field name
            'date' => 'nullable',
            'numero' => 'nullable',
            'nom' => 'nullable|string',
            'adresse' => 'nullable|string',  // Corrected field name
            'numero_telephone' => 'nullable|string',
            'motif_deplacement' => 'nullable|string',
            'heure_debut' => 'nullable',
            'heure_fin' => 'nullable',
            'nbr_passagers' => 'nullable|integer',
        ]);
    
        $data = $request->all();
        
        $data['chauffeur_id'] = $data['vehicule'] ?? null;
    
    
        unset($data['chauffeur1']);  
    
        Billet::create($data);
    
        return redirect()->route('billets.index')
            ->with('success', 'Billet created successfully.');
    }
    

    /**
     * Display the specified resource.
     */
    public function show(Billet $billet): View
    {
        $chauffeurs = Chauffeur::all();

        return view('billets.show', compact('billet'), compact('chauffeurs'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Billet $billet): View
    {
        $chauffeurs = Chauffeur::all();

        return view('billets.edit', compact('billet'), compact('chauffeurs'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Billet $billet): RedirectResponse
    {
        $request->validate([
            'vehicule' => 'nullable|string',
            'chauffeur1' => 'nullable|string',
            'telephone1' => 'nullable|string',
            'chauffeur2' => 'nullable|string',
            'telephone2' => 'nullable|string',
            'adresse' => 'nullable|string',
            'adresseclient' => 'nullable|string',
            'date' => 'nullable',
            'numero' => 'nullable',
            'nom' => 'nullable|string',
            'adresse' => 'nullable|string',
            'numero_telephone' => 'nullable|string',
            'motif_deplacement' => 'nullable|string',
            'heure_debut' => 'nullable',
            'heure_fin' => 'nullable',
            'nbr_passagers' => 'nullable|integer',
        ]);

        $billet->update($request->all());

        return redirect()->route('billets.index')
            ->with('success', 'Billet updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Billet $billet): RedirectResponse
    {
        $billet->delete();

        return redirect()->route('billets.index')
            ->with('success', 'Billet deleted successfully');
    }



    public function generatePDF($id)
    {
        $billet = Billet::findOrFail($id);
    
      
        $htmlContent = view('billets.create')->render();

        // Generate PDF
   
        $pdf = PDF::loadHTML($htmlContent)->setPaper('a2', 'landscape');
    
        $filename = 'billet_' . $billet->id . '.pdf';
    
        
        Storage::put('pdf/' . $filename, $pdf->output());
    
        
        $billet->update(['pdf_path' => 'pdf/' . $filename]);
    
        return redirect()->route('billets.index')->with('success', 'PDF saved successfully.');
    }
    



    public function sendEmail($id)
    {
        $billet = Billet::findOrFail($id);

        $pdfPath = storage_path($billet->pdf_path);

        $emailSubject = "Billet Information - {$billet->vehicule}";

        // Send email with PDF attachment
        Mail::to('recipient@example.com')->send(new BilletPdfEmail($pdfPath, $emailSubject));

        return redirect()->route('billets.index')->with('success', 'PDF sent via email successfully.');
    }


    public function printAndEmail()
    {
        // Render the view to a string
        $htmlContent = view('print.page')->render();

        // Generate PDF
        $pdf = PDF::loadHTML($htmlContent);
        $pdf->setPaper('a2', 'landscape'); // Set A2 landscape orientation
        $filename = 'billet_' . $billet->id . '.pdf';
    
        
        Storage::put('pdft/' . $filename, $pdf->output());
    
        
        $billet->update(['pdf_path' => 'pdf/' . $filename]);
        // // Save the PDF to a temporary file
        // $pdfPath = tempnam(sys_get_temp_dir(), 'printed_page');
        // $pdf->save($pdfPath);

        // // Send email with attachment
        // Mail::raw('Printing page content.', function ($message) use ($pdfPath) {
        //     $message->to('tibosouissi@gmail.com')
        //             ->subject('Printed Page')
        //             ->attach($pdfPath, ['as' => 'printed_page.pdf', 'mime' => 'application/pdf']);
        // });

        // // Delete the temporary PDF file
        // unlink($pdfPath);

        return redirect()->route('billets.index')->with('success', 'PDF sent via email successfully.');
    }
}
