<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\{Quotation, QuotationItem, Customer, Product, Lead};
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class QuotationController extends Controller
{
    public function index()
    {
        $currentUser = auth()->user();
        $quotations = Quotation::forUser($currentUser, 'quotations')
            ->with(['customer', 'lead'])
            ->latest()
            ->paginate(20);

        return view('quotations.index', compact('quotations'));
    }

    public function create(Request $request)
    {
        $currentUser = auth()->user();
        $lead = null;

        if ($request->filled('lead')) {
            $candidate = Lead::find($request->lead);
            if ($candidate && $currentUser->canAccessLead($candidate)) {
                $lead = $candidate;
            }
        }

        $customers = Customer::forUser($currentUser, 'customers')->orderBy('name')->get();
        $products = Product::where('active', true)->orderBy('name')->get();

        return view('quotations.create', compact('customers', 'products', 'lead'));
    }

    public function store(Request $request)
    {
        $d = $request->validate([
            'customer_id'         => 'required|exists:customers,id',
            'lead_id'             => 'nullable|exists:leads,id',
            'notes'               => 'nullable|string',
            'tax'                 => 'nullable|numeric|min:0',
            'items'               => 'required|array|min:1',
            'items.*.description' => 'required|string',
            'items.*.quantity'    => 'required|numeric|min:0.01',
            'items.*.unit_price'  => 'required|numeric|min:0',
            'items.*.discount'    => 'nullable|numeric|min:0',
        ]);

        $q = Quotation::create([
            'quote_no'    => 'QT-' . now()->format('Ym') . '-' . strtoupper(Str::random(5)),
            'customer_id' => $d['customer_id'],
            'lead_id'     => $d['lead_id'] ?? null,
            'status'      => 'draft',
            'notes'       => $d['notes'] ?? null,
        ]);

        $subtotal = 0;
        foreach ($d['items'] as $item) {
            $qty = (float) $item['quantity'];
            $price = (float) $item['unit_price'];
            $discount = (float) ($item['discount'] ?? 0);
            $line = max(0, $qty * $price - $discount);
            $subtotal += $line;
            $q->items()->create([
                'product_id'  => $item['product_id'] ?? null,
                'description' => $item['description'],
                'quantity'    => $qty,
                'unit_price'  => $price,
                'discount'    => $discount,
                'tax_rate'    => 0,
                'line_total'  => $line,
            ]);
        }

        $tax = (float) ($d['tax'] ?? 0);
        $q->update(['subtotal' => $subtotal, 'tax' => $tax, 'total' => $subtotal + $tax]);

        AuditLog::log('quotation_created', 'Quotations', "Created quotation '{$q->quote_no}' for total " . format_inr($q->total), $q);

        return redirect()->route('quotations.show', $q)->with('success', 'Quotation created successfully.');
    }

    public function show(Quotation $quotation)
    {
        $currentUser = auth()->user();
        if ($quotation->lead && !$currentUser->canAccessLead($quotation->lead)) {
            return response()->view('errors.403', [
                'permission' => 'quotations.view',
                'message'    => 'Access Denied: You do not have permission to access this quotation.'
            ], 403);
        }

        $quotation->load(['customer', 'items.product', 'lead']);
        return view('quotations.show', compact('quotation'));
    }

    public function status(Request $request, Quotation $quotation)
    {
        $s = $request->validate([
            'status' => 'required|in:draft,sent,accepted,rejected,expired,won,lost'
        ])['status'];

        $oldStatus = $quotation->status;
        $quotation->update(['status' => $s]);

        AuditLog::log('quotation_status_changed', 'Quotations', "Quotation '{$quotation->quote_no}' changed from {$oldStatus} to {$s}", $quotation);

        return back()->with('success', 'Quotation status updated.');
    }

    public function print(Quotation $quotation)
    {
        $currentUser = auth()->user();
        if ($quotation->lead && !$currentUser->canAccessLead($quotation->lead)) {
            return response()->view('errors.403', [
                'permission' => 'quotations.print',
                'message'    => 'Access Denied: You do not have permission to print this quotation.'
            ], 403);
        }

        $quotation->load(['customer', 'items.product', 'lead']);
        return view('quotations.print', compact('quotation'));
    }
}
