<?php

namespace App\Http\Controllers;

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

class InvoiceController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $invoices = Invoice::with(['customer', 'property', 'installment'])->latest()->paginate(15);
        return view('invoices.index', compact('invoices'));
    }

    public function create(Request $request)
    {
        $customers = \App\Models\Customer::all();
        $properties = \App\Models\Property::all();
        $installment = null;
        
        if ($request->has('installment_id')) {
            $installment = \App\Models\Installment::with(['installmentPlan.customer', 'installmentPlan.property'])->find($request->installment_id);
        }
        
        return view('invoices.create', compact('customers', 'properties', 'installment'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'property_id' => 'nullable|exists:properties,id',
            'installment_id' => 'nullable|exists:installments,id',
            'amount' => 'required|numeric|min:0',
            'date' => 'required|date',
            'type' => 'required|string',
            'payment_method' => 'required|string',
            'status' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        // Generate unique invoice number
        $validated['invoice_number'] = 'INV-' . strtoupper(uniqid());

        $invoice = Invoice::create($validated);
        
        // Update installment status if linked
        if ($invoice->installment_id && $invoice->status === 'Paid') {
            $installment = \App\Models\Installment::find($invoice->installment_id);
            if ($installment) {
                $installment->update([
                    'status' => 'Paid',
                    'amount_paid' => $invoice->amount,
                    'paid_date' => $invoice->date
                ]);
            }
        }

        // Ledger Automation (Rule 14): Auto-post double-entry logs for Invoice Generation
        if ($invoice->property_id) {
            $property = \App\Models\Property::with('block.project')->find($invoice->property_id);
            $projectId = $property && $property->block ? $property->block->project_id : null;

            if ($projectId) {
                // 1. Debit Customer (Accounts Receivable)
                \App\Models\LedgerEntry::create([
                    'account_type' => \App\Models\Customer::class,
                    'account_id' => $invoice->customer_id,
                    'reference_type' => \App\Models\Invoice::class,
                    'reference_id' => $invoice->id,
                    'type' => 'Debit',
                    'amount' => $invoice->amount,
                    'description' => 'Invoice ' . $invoice->invoice_number . ' generated',
                    'date' => $invoice->date,
                ]);

                // 2. Credit Project (Sales/Revenue)
                \App\Models\LedgerEntry::create([
                    'account_type' => \App\Models\Project::class,
                    'account_id' => $projectId,
                    'reference_type' => \App\Models\Invoice::class,
                    'reference_id' => $invoice->id,
                    'type' => 'Credit',
                    'amount' => $invoice->amount,
                    'description' => 'Revenue from Invoice ' . $invoice->invoice_number,
                    'date' => $invoice->date,
                ]);
            }
        }

        // Notify Customer in Portal
        $customer = \App\Models\Customer::find($invoice->customer_id);
        if ($customer && $customer->user_id) {
            $user = \App\Models\User::find($customer->user_id);
            if ($user) {
                $user->notify(new \App\Notifications\SystemNotification('Invoice Generated', 'A new invoice (' . $invoice->invoice_number . ') has been generated for PKR ' . number_format($invoice->amount)));
            }
        }

        // WhatsApp Notification
        try {
            $whatsapp = app(\App\Services\WhatsAppService::class);
            $customer = \App\Models\Customer::find($invoice->customer_id);
            if ($customer && $customer->phone) {
                $whatsapp->sendTemplateMessage(
                    $customer->phone,
                    'invoice_generated',
                    [
                        ['type' => 'text', 'text' => $customer->name],
                        ['type' => 'text', 'text' => $invoice->invoice_number],
                        ['type' => 'text', 'text' => number_format($invoice->amount)]
                    ]
                );
            }
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error("Failed to trigger WhatsApp for Invoice: " . $e->getMessage());
        }

        return redirect()->route('invoices.show', $invoice)->with('success', 'Invoice generated successfully.');
    }

    public function show(Invoice $invoice)
    {
        $invoice->load(['customer', 'property', 'installment.installmentPlan']);
        $settings = \App\Models\Setting::pluck('value', 'key');
        
        return view('invoices.show', compact('invoice', 'settings'));
    }

    public function update(Request $request, Invoice $invoice)
    {
        $validated = $request->validate([
            'status' => 'required|string',
        ]);

        $oldStatus = $invoice->status;
        $invoice->update(['status' => $validated['status']]);

        // If status changed to Paid, update installment and notify customer
        if ($oldStatus !== 'Paid' && $invoice->status === 'Paid') {
            if ($invoice->installment_id) {
                $installment = \App\Models\Installment::find($invoice->installment_id);
                if ($installment) {
                    $installment->update([
                        'status' => 'Paid',
                        'amount_paid' => $invoice->amount,
                        'paid_date' => now()
                    ]);
                }
            }

            // Notify Customer
            $customer = \App\Models\Customer::find($invoice->customer_id);
            if ($customer && $customer->user_id) {
                $user = \App\Models\User::find($customer->user_id);
                if ($user) {
                    $user->notify(new \App\Notifications\SystemNotification('Payment Approved', 'Your payment for Invoice ' . $invoice->invoice_number . ' has been approved!'));
                }
            }
        }

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