<?php

namespace App\Http\Controllers;

use App\Models\Machine;
use App\Models\Quotation;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Validator;
use Dompdf\Dompdf;
use Dompdf\Options;

class QuotationController extends Controller
{
    public function create()
    {
        $machines = Machine::where('active', true)
            ->orderBy('name')
            ->select('id', 'name', 'slug', 'category', 'brand', 'gallery_json')
            ->get();

        // Obtener categorías con conteo de máquinas
        $categoriesWithCount = Machine::where('active', true)
            ->selectRaw('category, COUNT(*) as count')
            ->groupBy('category')
            ->orderBy('category')
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item->category,
                    'count' => $item->count,
                ];
            });

        return Inertia::render('Quotations/Create', [
            'machines' => $machines,
            'categoriesWithCount' => $categoriesWithCount,
        ]);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'visitor_name' => 'required|string|max:255',
            'visitor_email' => 'required|email|max:255',
            'visitor_phone' => 'required|string|max:20',
            'start_date' => 'required|date|after_or_equal:today',
            'end_date' => 'required|date|after:start_date',
            'machine_ids' => 'required|array|min:1',
            'machine_ids.*' => 'exists:machines,id',
            'notes' => 'nullable|string|max:1000',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $quotation = Quotation::create([
            'visitor_name' => $request->visitor_name,
            'visitor_email' => $request->visitor_email,
            'visitor_phone' => $request->visitor_phone,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'status' => 'pending',
            'notes' => $request->notes,
        ]);

        // Attach machines to quotation
        $machinesData = [];
        foreach ($request->machine_ids as $machineId) {
            $machinesData[$machineId] = ['quantity' => 1];
        }
        $quotation->machines()->attach($machinesData);

        return redirect()->route('quotations.success', $quotation->id)
            ->with('success', 'Cotización enviada exitosamente. Nos pondremos en contacto contigo pronto.');
    }

    public function success($id)
    {
        $quotation = Quotation::with('machines')->findOrFail($id);

        return Inertia::render('Quotations/Success', [
            'quotation' => $quotation,
        ]);
    }

    public function downloadPdf($id)
    {
        $quotation = Quotation::with('machines')->findOrFail($id);

        // Find logo path
        $logoPath1 = public_path('storage/logoAkiyan.png');
        $logoPath2 = storage_path('app/public/logoAkiyan.png');
        $logoPath = file_exists($logoPath1) ? $logoPath1 : (file_exists($logoPath2) ? $logoPath2 : null);

        // Configure DomPDF options
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');
        $options->set('chroot', [
            public_path(),
            storage_path('app/public'),
            base_path(),
        ]);

        $dompdf = new Dompdf($options);

        // Render the view
        $html = view('quotations.pdf', compact('quotation', 'logoPath'))->render();
        $dompdf->loadHtml($html);

        // Set paper size and orientation
        $dompdf->setPaper('A4', 'portrait');

        // Render PDF
        $dompdf->render();

        // Generate filename
        $filename = 'cotizacion-' . str_pad($quotation->id, 6, '0', STR_PAD_LEFT) . '.pdf';

        // Return PDF as download
        return response()->streamDownload(function () use ($dompdf) {
            echo $dompdf->output();
        }, $filename, [
            'Content-Type' => 'application/pdf',
        ]);
    }
}
