<?php

namespace App\Http\Controllers;

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

class QuotationController extends Controller
{
    public function index()
    {
        $quotations = Quotation::with('items')->orderBy('date', 'desc')->get();
        return view('quotations.index', compact('quotations'));
    }

    public function sales()
    {
        $quotations = Quotation::with('items')->where('status', 'sale')->orderBy('date', 'desc')->get();
        return view('quotations.sales', compact('quotations'));
    }

    public function create()
    {
        return view('quotations.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'bill_to' => 'nullable|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'mobile' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'date' => 'nullable|date',
            'note' => 'nullable|string',
            'status' => 'nullable|string',

            'items.description.*' => 'nullable|string',
            'items.qty.*' => 'nullable|integer|min:0',
            'items.rate.*' => 'nullable|numeric|min:0',
        ]);

        // compute amounts and totals
        $subtotal = 0;
        $itemsData = [];

        if ($request->has('items')) {
            foreach ($request->items['description'] as $index => $desc) {
                $qty = (float) $request->items['qty'][$index];
                $rate = (float) $request->items['rate'][$index];
                $amount = $qty * $rate;
                $subtotal += $amount;
                $itemsData[] = [
                    'description' => $desc,
                    'qty' => $qty,
                    'rate' => $rate,
                    'amount' => $amount,
                ];
            }
        }

        $quotation = Quotation::create([
            'quotation_number' => Quotation::generateQuotationNumber(),
            'bill_to' => $data['bill_to'] ?? null,
            'company_name' => $data['company_name'] ?? null,
            'mobile' => $data['mobile'] ?? null,
            'email' => $data['email'] ?? null,
            'date' => $data['date'] ?? now(),
            'subtotal' => $subtotal,
            'total' => $subtotal,
            'in_word' => $this->numberToWords($subtotal),
            'note' => $data['note'] ?? null,
            'status' => $data['status'] ?? 'pending',
        ]);

        foreach ($itemsData as $item) {
            $quotation->items()->create($item);
        }

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

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

    public function edit(Quotation $quotation)
    {
        $quotation->load('items');
        return view('quotations.edit', compact('quotation'));
    }

    public function update(Request $request, Quotation $quotation)
    {
        $data = $request->validate([
            'bill_to' => 'nullable|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'mobile' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'date' => 'nullable|date',
            'note' => 'nullable|string',
            'status' => 'nullable|string',

            'items.description.*' => 'nullable|string',
            'items.qty.*' => 'nullable|integer|min:0',
            'items.rate.*' => 'nullable|numeric|min:0',
        ]);

        $subtotal = 0;
        $itemsData = [];

        if ($request->has('items')) {
            foreach ($request->items['description'] as $index => $desc) {
                $qty = (float) $request->items['qty'][$index];
                $rate = (float) $request->items['rate'][$index];
                $amount = $qty * $rate;
                $subtotal += $amount;
                $itemsData[] = [
                    'description' => $desc,
                    'qty' => $qty,
                    'rate' => $rate,
                    'amount' => $amount,
                ];
            }
        }

        $quotation->update([
            'bill_to' => $data['bill_to'] ?? null,
            'company_name' => $data['company_name'] ?? null,
            'mobile' => $data['mobile'] ?? null,
            'email' => $data['email'] ?? null,
            'date' => $data['date'] ?? now(),
            'subtotal' => $subtotal,
            'total' => $subtotal,
            'in_word' => $this->numberToWords($subtotal),
            'note' => $data['note'] ?? null,
            'status' => $data['status'] ?? $quotation->status,
        ]);

        // sync items: delete old and create new
        $quotation->items()->delete();
        foreach ($itemsData as $item) {
            $quotation->items()->create($item);
        }

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

    public function destroy(Quotation $quotation)
    {
        $quotation->delete();
        return redirect()->route('quotations.index')->with('success', 'Quotation deleted');
    }

    public function updateStatus(Request $request, Quotation $quotation)
    {
        $validated = $request->validate([
            'status' => 'required|in:pending,sale,not_sale',
        ]);
        $quotation->update(['status' => $validated['status']]);
        return back()->with('success', 'Status updated');
    }

    public function print()
    {
        $quotations = Quotation::with('items')->orderBy('date', 'desc')->get();
        return view('quotations.print', compact('quotations'));
    }

    /**
     * Convert number to words (simple english) for invoice.
     */
    protected function numberToWords($number)
    {
        if (!is_numeric($number)) {
            return '';
        }
        // Using built-in NumberFormatter if available
        if (class_exists('NumberFormatter')) {
            $formatter = new \NumberFormatter('en', \NumberFormatter::SPELLOUT);
            return ucfirst($formatter->format($number)) . ' only';
        }

        return $number;
    }
}
