<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\Account;
use App\Models\Cashbook;
use App\Models\JournalEntry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class InvoicePaymentController extends Controller
{
    
    /**
     * Display a listing of all payments received for invoices.
     */
    public function index()
    {
        $companyId = Auth::user()->current_company_id;

        // We fetch entries from the cashbook that are specifically linked to an invoice
        $payments = Cashbook::with(['customer', 'invoice'])
            ->where('company_id', $companyId)
            ->whereNotNull('invoice_id')
            ->orderBy('transaction_date', 'desc')
            ->paginate(15);

        return view('sales.payments.index', compact('payments'));
    }
    
    
    public function createPayment($invoiceId)
{
    $companyId = Auth::user()->current_company_id;
    $invoice = Invoice::with('customer')->where('company_id', $companyId)->findOrFail($invoiceId);

    // FIX: Filter directly by Account Type IDs 1 (Bank) and 2 (Cash)
    // These IDs are confirmed in your account_types.sql file
    $bankAccounts = Account::where('company_id', $companyId)
        ->whereIn('account_type_id', [1, 2, 16]) // 1=Bank, 2=Cash, 16=Mobile Money
        ->where('is_active', 1)
        ->get();

    return view('invoices.payments.create', compact('invoice', 'bankAccounts'));
}
   public function storePayment(Request $request, $invoiceId)
{
    $request->validate([
        'cash_bank_account_id' => 'required|exists:accounts,id',
        'amount_received' => 'required|numeric|min:0.01',
        'transaction_date' => 'required|date',
        'reference' => 'required|string',
    ]);

    try {
        return DB::transaction(function () use ($request, $invoiceId) {
            $companyId = Auth::user()->current_company_id;
            $invoice = Invoice::findOrFail($invoiceId);

            // 1. Identify Accounts
            $bankAccount = Account::findOrFail($request->cash_bank_account_id);
            $arAccount = Account::where('company_id', $companyId)
                ->where('account_type_id', 3) // Trade Receivables
                ->first();

            if (!$arAccount) {
                throw new \Exception("Accounting Configuration Error: 'Trade Receivables' account (Type 3) not found.");
            }

            // 2. Determine Payment Method (Satisfying the DB Constraint)
            // If it's account type 2, it's Cash. Otherwise, treat as Transfer/Electronic.
            $method = ($bankAccount->account_type_id == 2) ? 'Cash' : 'Transfer';

            // 3. Update Invoice Totals
            $invoice->total_paid += $request->amount_received;
            $invoice->outstanding_balance -= $request->amount_received;
            
            if ($invoice->outstanding_balance <= 0) {
                $invoice->status = 'paid';
            }
            $invoice->save();

            // 4. Record in Cashbook (Now including payment_method)
            Cashbook::create([
                'company_id'               => $companyId,
                'customer_id'              => $invoice->customer_id,
                'invoice_id'               => $invoice->id,
                'cash_bank_account_id'     => $request->cash_bank_account_id,
                'corresponding_account_id' => $arAccount->id,
                'payment_method'           => $method, // CRITICAL FIX
                'transaction_date'         => $request->transaction_date,
                'reference'                => $request->reference,
                'debit'                    => $request->amount_received,
                'credit'                   => 0,
                'status'                   => 'cleared',
                'memo'                     => $request->memo,
                'created_by'               => Auth::id(),
            ]);

            // 5. Record Double-Entry in Journal
            // DEBIT Bank
            JournalEntry::create([
                'company_id'       => $companyId,
                'customer_id'      => $invoice->customer_id,
                'invoice_id'       => $invoice->id,
                'account_id'       => $request->cash_bank_account_id,
                'transaction_date' => $request->transaction_date,
                'reference'        => $request->reference,
                'description'      => "Payment received: " . $invoice->invoice_no,
                'debit'            => $request->amount_received,
                'credit'           => 0,
                'transource'       => 'Payment',
                'user_id'          => Auth::id()
            ]);

            // CREDIT Trade Receivables
            JournalEntry::create([
                'company_id'       => $companyId,
                'customer_id'      => $invoice->customer_id,
                'invoice_id'       => $invoice->id,
                'account_id'       => $arAccount->id,
                'transaction_date' => $request->transaction_date,
                'reference'        => $request->reference,
                'description'      => "AR Credit: " . $invoice->invoice_no,
                'debit'            => 0,
                'credit'           => $request->amount_received,
                'transource'       => 'Payment',
                'user_id'          => Auth::id()
            ]);

            return redirect()->route('invoices.show', $invoice->id)
                ->with('success', 'Payment of K' . number_format($request->amount_received, 2) . ' posted successfully.');
        });
    } catch (\Exception $e) {
        return redirect()->back()->withInput()->with('error', 'Critical Error: ' . $e->getMessage());
    }
}


    private function postPaymentToLedger($invoice, $cashbook)
    {
        // DR Bank
        JournalEntry::create([
            'company_id' => $invoice->company_id,
            'account_id' => $cashbook->cash_bank_account_id,
            'transaction_date' => $cashbook->transaction_date,
            'reference' => $cashbook->reference,
            'description' => "Payment for Invoice: " . $invoice->invoice_no,
            'debit' => $cashbook->debit,
            'credit' => 0,
            'user_id' => Auth::id(),
        ]);

        // CR Accounts Receivable
        $arAccount = Account::where('company_id', $invoice->company_id)->where('slug', 'accounts-receivable')->first();
        JournalEntry::create([
            'company_id' => $invoice->company_id,
            'account_id' => $arAccount->id,
            'customer_id' => $invoice->customer_id,
            'transaction_date' => $cashbook->transaction_date,
            'reference' => $cashbook->reference,
            'description' => "AR Credit: " . $invoice->customer->name,
            'debit' => 0,
            'credit' => $cashbook->debit,
            'user_id' => Auth::id(),
        ]);
    }
}