<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Product;
use App\Models\Customer;
use App\Models\SalesDashboard;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index(Request $request)
    {
        $query = Invoice::where('user_id', auth()->id())
            ->with('customer');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('from_date')) {
            $query->whereDate('date', '>=', $request->from_date);
        }

        if ($request->filled('to_date')) {
            $query->whereDate('date', '<=', $request->to_date);
        }

        $invoices = $query->orderBy('date', 'desc')->paginate(20);

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

    public function create()
    {
        $customers = Customer::where('user_id', auth()->id())->orderBy('name')->get();
        $products = Product::where('user_id', auth()->id())->where('current_stock', '>', 0)->orderBy('name')->get();

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'invoice_date' => 'required|date',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|integer|min:1',
            'items.*.unit_price' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $invoice = auth()->user()->invoices()->create([
            'customer_id' => $validated['customer_id'],
            'date' => $validated['invoice_date'],
            'status' => 'unpaid',
            'notes' => $validated['notes'] ?? null,
            'subtotal' => 0,
            'tax' => 0,
            'discount' => 0,
            'total' => 0,
            'paid' => 0,
            'due' => 0,
        ]);

        $totalAmount = 0;

        foreach ($validated['items'] as $item) {
            $product = Product::find($item['product_id']);
            $subtotal = $item['quantity'] * $item['unit_price'];
            $totalAmount += $subtotal;

            // Calculate COGS and profit
            $cogs = $product->purchase_price * $item['quantity'] ?? 0;
            $profit = $subtotal - $cogs;

            // Stock will be automatically decremented by InvoiceItemObserver
            // Also decrement directly as backup to ensure it happens
            $invoice->items()->create([
                'product_id' => $item['product_id'],
                'quantity' => $item['quantity'],
                'unit_price' => $item['unit_price'],
                'total' => $subtotal,
                'purchase_price' => $product->purchase_price ?? 0,
                'cogs' => $cogs,
                'profit' => $profit,
            ]);

            // Direct stock decrement backup
            if ($product && $product->current_stock >= $item['quantity']) {
                $product->decrement('current_stock', $item['quantity']);
            }
        }

        $invoice->update([
            'subtotal' => $totalAmount,
            'total' => $totalAmount,
            'due' => $totalAmount,
        ]);

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

    public function show(Invoice $invoice)
    {
        $this->authorize('view', $invoice);
        $invoice->load('items.product', 'customer');

        return view('invoices.show', compact('invoice'));
    }

    public function edit(Invoice $invoice)
    {
        $this->authorize('update', $invoice);

        $customers = Customer::where('user_id', auth()->id())->orderBy('name')->get();
        $products = Product::where('user_id', auth()->id())->orderBy('name')->get();
        $invoice->load('items');

        return view('invoices.edit', compact('invoice', 'customers', 'products'));
    }

    public function update(Request $request, Invoice $invoice)
    {
        $this->authorize('update', $invoice);

        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'date' => 'required|date',
            'status' => 'required|in:paid,partial,unpaid',
            'notes' => 'nullable|string',
        ]);

        $invoice->update($validated);

        // Update linked sales_dashboard record if exists
        $salesDashboard = SalesDashboard::where('invoice_id', $invoice->id)->first();
        if ($salesDashboard) {
            // Get first item from invoice
            $firstItem = $invoice->items()->first();

            $salesDashboard->update([
                'date' => $validated['date'],
                'customer_id' => $validated['customer_id'],
                'product' => $firstItem && $firstItem->product ? $firstItem->product->name : null,
                'qty' => $firstItem ? $firstItem->quantity : null,
                'sales' => $firstItem ? $firstItem->unit_price : null,
                'particulars' => $validated['notes'],
                'payment' => $invoice->paid,
                'due' => $invoice->due,
                'cogs' => $invoice->items()->sum('cogs'),
                'gross_profit' => $invoice->items()->sum('profit'),
            ]);
        }

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

    public function destroy(Invoice $invoice)
    {
        $this->authorize('delete', $invoice);

        // Restore stock for each item before deletion
        foreach ($invoice->items as $item) {
            if ($item->product) {
                $item->product->increment('current_stock', $item->quantity);
            }
        }

        // Delete linked sales_dashboard record if exists
        $salesDashboard = SalesDashboard::where('invoice_id', $invoice->id)->first();
        if ($salesDashboard) {
            $salesDashboard->delete();
        }

        // Stock will be automatically restored by InvoiceItemObserver when items are deleted
        $invoice->delete();

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

    public function print(Invoice $invoice)
    {
        $this->authorize('view', $invoice);
        $invoice->load('items.product', 'customer');

        return view('invoices.print', compact('invoice'));
    }
}
