<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Loan;
use App\Models\SavingsTransaction;
use App\Models\Client;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ProcessingController extends Controller
{
    public function invoicing()
    {
        $loans = Loan::with(['client'])->whereIn('status', ['approved', 'disbursed'])->get();
        return view('processing.invoicing', compact('loans'));
    }

    /**
     * Store a new invoice from processing/invoicing
     */
    public function storeInvoice(Request $request)
    {
        $request->validate([
            'invoice_number' => 'required|string|unique:invoices,invoice_number',
            'invoice_date' => 'required|date',
            'customer_id' => 'required|exists:clients,id',
            'due_date' => 'nullable|date|after:invoice_date',
            'description' => 'nullable|string|max:1000',
        ]);

        try {
            $invoice = DB::transaction(function () use ($request) {
                // Calculate totals from items
                $subtotal = 0;
                $totalDiscount = 0;
                $taxAmount = 0;

                if ($request->has('items')) {
                    foreach ($request->items as $item) {
                        $quantity = $item['quantity'] ?? 1;
                        $unitPrice = $item['price'] ?? 0;
                        $discountPercent = $item['discount'] ?? 0;

                        $lineTotal = $quantity * $unitPrice;
                        $discountAmount = $lineTotal * ($discountPercent / 100);
                        $subtotal += $lineTotal - $discountAmount;
                        $totalDiscount += $discountAmount;
                    }
                }

                $taxAmount = $subtotal * 0.1; // 10% tax, adjust as needed
                $total = $subtotal + $taxAmount;

                // Generate invoice number in INV000001 format
                $invoiceNumber = $this->generateInvoiceNumber();

                // Create invoice record
                $invoice = Invoice::create([
                    'invoice_number' => $invoiceNumber,
                    'invoice_date' => $request->invoice_date,
                    'customer_id' => $request->customer_id,
                    'due_date' => $request->due_date,
                    'description' => $request->description,
                    'subtotal' => $subtotal,
                    'discount_total' => $totalDiscount,
                    'tax_amount' => $taxAmount,
                    'total' => $total,
                    'status' => 'draft',
                    'created_by' => Auth::id(),
                ]);

                // Store invoice items if provided
                if ($request->has('items')) {
                    foreach ($request->items as $item) {
                        $quantity = $item['quantity'] ?? 1;
                        $unitPrice = $item['price'] ?? 0;
                        $discountPercent = $item['discount'] ?? 0;

                        $lineTotal = $quantity * $unitPrice;
                        $discountAmount = $lineTotal * ($discountPercent / 100);
                        $lineSubtotal = $lineTotal - $discountAmount;
                        $lineTax = $lineSubtotal * 0.1; // 10% tax

                        InvoiceItem::create([
                            'invoice_id' => $invoice->id,
                            'item_description' => $item['item_description'] ?? $item['description'] ?? 'Item',
                            'quantity' => $quantity,
                            'unit_price' => $unitPrice,
                            'discount_percent' => $discountPercent,
                            'discount_amount' => $discountAmount,
                            'tax_rate' => 10,
                            'tax_amount' => $lineTax,
                            'line_total' => $lineSubtotal + $lineTax,
                        ]);
                    }
                }

                return $invoice;
            });

            Log::info('Invoice created from processing', ['invoice_id' => $invoice->id, 'invoice_number' => $invoice->invoice_number]);

            return redirect()->route('accounts.invoices.show', $invoice->id)
                ->with('success', 'Invoice created successfully! Invoice Number: ' . $invoice->invoice_number)
                ->with('show_print_prompt', true);

        } catch (\Exception $e) {
            Log::error('Error creating invoice from processing', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Failed to create invoice: ' . $e->getMessage());
        }
    }

    /**
     * Generate unique invoice number in INV000001 format
     */
    private function generateInvoiceNumber()
    {
        $lastInvoice = Invoice::orderBy('invoice_number', 'desc')->first();

        if ($lastInvoice) {
            // Extract the sequence number from INV000001 format and increment
            $sequence = intval(substr($lastInvoice->invoice_number, 3)) + 1;
        } else {
            $sequence = 1;
        }

        // Format with leading zeros (6 digits) - INV000001
        $sequenceStr = str_pad($sequence, 6, '0', STR_PAD_LEFT);

        return "INV{$sequenceStr}";
    }

    public function receipts()
    {
        $transactions = SavingsTransaction::with(['savingsAccount.client'])
        ->whereIn('type', ['deposit', 'repayment'])
        ->latest()
        ->paginate(20);

        return view('processing.receipts', compact('transactions'));
    }

    public function payments()
    {
        $transactions = SavingsTransaction::with(['savingsAccount.client'])
        ->where('type', 'withdrawal')
        ->latest()
        ->paginate(20);

        return view('processing.payments', compact('transactions'));
    }

    public function transactions()
    {
        $transactions = SavingsTransaction::with(['savingsAccount.client'])
        ->latest()
        ->paginate(50);

        return view('processing.transactions', compact('transactions'));
    }
}
