<?php

namespace App\Http\Controllers;

use App\Models\Quotation;
use Illuminate\Http\Request;

class QuotationController extends Controller
{
    public function index()
    {
        $quotations = Quotation::with(['customer', 'property'])->latest()->paginate(15);
        return view('quotations.index', compact('quotations'));
    }

    public function create()
    {
        $customers = \App\Models\Customer::all();
        $leads = \App\Models\Lead::all();
        $properties = \App\Models\Property::where('status', 'Available')->get();
        return view('quotations.create', compact('customers', 'leads', 'properties'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'nullable|exists:customers,id',
            'lead_id' => 'nullable|exists:leads,id',
            'property_id' => 'required|exists:properties,id',
            'base_price' => 'required|numeric|min:0',
            'discount' => 'nullable|numeric|min:0',
            'development_charges' => 'nullable|numeric|min:0',
            'other_charges' => 'nullable|numeric|min:0',
            'valid_until' => 'required|date',
        ]);

        if (empty($validated['customer_id']) && empty($validated['lead_id'])) {
            return back()->withInput()->withErrors(['customer_id' => 'Either a Customer or a Lead must be selected.']);
        }

        $property = \App\Models\Property::findOrFail($validated['property_id']);
        if (!in_array($property->status, ['Available'])) {
            return back()->withInput()->with('error', 'Cannot generate a quotation for a property that is already sold or reserved.');
        }

        $validated['discount'] = $validated['discount'] ?? 0;
        $validated['development_charges'] = $validated['development_charges'] ?? 0;
        $validated['other_charges'] = $validated['other_charges'] ?? 0;
        
        $validated['net_price'] = $validated['base_price'] - $validated['discount'] + $validated['development_charges'] + $validated['other_charges'];
        $validated['status'] = 'Draft';

        Quotation::create($validated);

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

    public function show(Quotation $quotation)
    {
        return view('quotations.show', compact('quotation'));
    }
}
