<?php

namespace App\Http\Controllers;

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

class TransactionController extends Controller
{
    public function index()
    {
        $transactions = Transaction::with(['customer', 'invoice'])->latest()->paginate(20);
        return view('transactions.index', compact('transactions'));
    }

    public function create()
    {
        $customers = \App\Models\Customer::all();
        $invoices = \App\Models\Invoice::where('status', '!=', 'Paid')->get();
        return view('transactions.create', compact('customers', 'invoices'));
    }

    public function store(Request $request, \App\Services\BalanceService $balanceService)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'invoice_id' => 'nullable|exists:invoices,id',
            'amount' => 'required|numeric|min:0',
            'payment_method' => 'required|string',
            'receipt_number' => 'nullable|string|unique:transactions,receipt_number',
            'cheque_number' => 'nullable|string|unique:transactions,cheque_number',
            'is_advance' => 'boolean',
            'proof_path' => 'nullable|file|max:10240',
        ]);

        // Duplicate Check (Rule 6 part)
        $duplicate = Transaction::where('customer_id', $validated['customer_id'])
            ->where('amount', $validated['amount'])
            ->whereDate('created_at', now()->toDateString())
            ->exists();

        if ($duplicate) {
            return back()->withInput()->with('error', 'A duplicate transaction with the same amount was detected today.');
        }

        // Smart Balance & Outstanding Check (Rule 6)
        if (!empty($validated['invoice_id'])) {
            $invoice = \App\Models\Invoice::with('property')->find($validated['invoice_id']);
            if ($invoice && $invoice->property_id) {
                // Find booking
                $booking = \App\Models\Booking::where('property_id', $invoice->property_id)
                    ->where('customer_id', $validated['customer_id'])
                    ->first();

                if ($booking && empty($validated['is_advance'])) {
                    if ($balanceService->exceedsOutstandingBalance($booking, $validated['amount'])) {
                        return back()->withInput()->with('error', 'Payment amount exceeds the outstanding balance. Mark as advance if intentional.');
                    }
                }
            }
        }

        $proofPath = null;
        if ($request->hasFile('proof_path')) {
            $proofPath = $request->file('proof_path')->store('payment_proofs', 'public');
        }
        $validated['proof_path'] = $proofPath;

        $validated['status'] = 'Pending';
        Transaction::create($validated);

        return redirect()->route('transactions.index')->with('success', 'Payment recorded successfully.');
    }

    public function approve(Transaction $transaction, \App\Services\CommissionService $commissionService, \App\Services\WhatsAppService $whatsAppService)
    {
        $transaction->update(['status' => 'Approved']);
        if ($transaction->invoice) {
            $transaction->invoice->update(['status' => 'Paid']);
        }

        // Ledger Automation (Rule 14): Auto-post double-entry logs
        // 1. Debit Cash/Bank
        \App\Models\LedgerEntry::create([
            'account_type' => $transaction->payment_method === 'Cash' ? 'Cash' : 'Bank',
            'account_id' => null,
            'reference_type' => \App\Models\Transaction::class,
            'reference_id' => $transaction->id,
            'type' => 'Debit',
            'amount' => $transaction->amount,
            'description' => 'Payment received via ' . $transaction->payment_method,
            'date' => now()->toDateString(),
        ]);

        // 2. Credit Customer
        \App\Models\LedgerEntry::create([
            'account_type' => \App\Models\Customer::class,
            'account_id' => $transaction->customer_id,
            'reference_type' => \App\Models\Transaction::class,
            'reference_id' => $transaction->id,
            'type' => 'Credit',
            'amount' => $transaction->amount,
            'description' => 'Payment credited to customer account',
            'date' => now()->toDateString(),
        ]);

        // 3. Smart Commission (Rule 10)
        $commissionService->generateForTransaction($transaction);

        // 4. Send WhatsApp Notification (Rule 18)
        $templateId = \App\Models\Setting::where('key', 'wa_template_payment_received')->value('value');
        if ($templateId && $transaction->customer->phone) {
            // e.g. body variables: [Name, Amount]
            $bodyVariables = [
                $transaction->customer->full_name ?? 'Customer',
                number_format($transaction->amount)
            ];
            $whatsAppService->sendTemplateMessage($transaction->customer->phone, $templateId, $bodyVariables);
        }

        return back()->with('success', 'Transaction approved, invoice marked as Paid, ledger entries posted, and commission calculated automatically.');
    }

    public function reject(Transaction $transaction)
    {
        $transaction->update(['status' => 'Rejected']);
        return back()->with('success', 'Transaction rejected.');
    }

    public function destroy(Transaction $transaction)
    {
        if (auth()->user()->hasRole('Super Admin')) {
            $transaction->delete();
            return back()->with('success', 'Transaction deleted successfully.');
        }
        return back()->with('error', 'Unauthorized access.');
    }
}
