<?php

namespace App\Http\Controllers;

use App\Models\Receipt;
use App\Models\CustomerAccount;
use App\Models\PaymentType;
use App\Models\GeneralLedger;
use App\Models\DocumentHeader;
use App\Models\CashbookEntry;
use App\Models\CompanySettings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class ReceiptController extends Controller
{
    public function create()
    {
        $receiptNumber = Receipt::getNextReceiptNumber();
        $customers = CustomerAccount::all();
        $paymentTypes = PaymentType::all();
        $accounts = GeneralLedger::with('subAccounts')->get();

        return view('receipts.create', compact(
            'receiptNumber',
            'customers',
            'paymentTypes',
            'accounts'
        ));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'receipt_number' => 'required|unique:receipts,receipt_number',
            'receipt_date' => 'required|date',
            'customer_id' => 'required|exists:customer_accounts,id',
            'payment_type_id' => 'required|exists:payment_types,id',
            'lines' => 'required|array|min:1',
            'lines.*.description' => 'required|string|max:255',
            'lines.*.invoice_id' => 'nullable|exists:document_headers,id',
            'lines.*.deposit_account_id' => 'required|exists:main_accounts,id',
            'lines.*.amount' => 'required|numeric|min:0.01',
        ]);

        DB::beginTransaction();

        try {
            $totalAmount = collect($validated['lines'])->sum('amount');

            $invoiceId = null;
            foreach ($validated['lines'] as $line) {
                if (!empty($line['invoice_id'])) {
                    $invoiceId = $line['invoice_id'];
                    break;
                }
            }

            $receipt = Receipt::create([
                'receipt_number'     => $validated['receipt_number'],
                'receipt_date'       => $validated['receipt_date'],
                'customer_id'        => $validated['customer_id'],
                'payment_type_id'    => $validated['payment_type_id'],
                'deposit_account_id' => $validated['lines'][0]['deposit_account_id'],
                'total_amount'       => $totalAmount,
                'invoice_id'         => $invoiceId,
                'status'             => 'processed'
            ]);

            DB::commit();

            return redirect()->route('receipts.create')
                ->with('success', 'Receipt processed successfully!')
                ->with('processed_receipt_id', $receipt->id);

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Error processing receipt: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function getInvoiceOutstanding($invoiceId)
    {
        $invoice = DocumentHeader::find($invoiceId);
        if (!$invoice) {
            return response()->json(['outstanding' => 0]);
        }

        // ✅ Same calculation as in CashbookController
        $receiptsPaid = Receipt::where('customer_id', $invoice->customer_account_id)
            ->where('invoice_id', $invoiceId)
            ->where('status', 'processed')
            ->sum('total_amount');

        $cashbookPaid = CashbookEntry::where('reference_id', $invoiceId)
            ->where('reference_type', 'invoice')
            ->where('module', 'AR')
            ->where('tr_code', 'Receipt')
            ->sum('dr_amount');

        $totalPaid = $receiptsPaid + $cashbookPaid;
        $outstanding = max(0, $invoice->inclusive_total - $totalPaid);

        return response()->json([
            'outstanding'     => $outstanding,
            'invoice_total'   => $invoice->inclusive_total,
            'invoice_number'  => $invoice->document_number
        ]);
    }

    public function print($id)
    {
        $receipt = Receipt::with(['customer', 'paymentType', 'depositAccount', 'invoice'])
            ->findOrFail($id);
            
        $company = CompanySettings::first();

        $pdf = Pdf::loadView('receipts.print', compact('receipt', 'company'));
        
        return $pdf->download("receipt-{$receipt->receipt_number}.pdf");
    }

    public function getCustomerInvoices($customerId)
    {
        $invoices = DocumentHeader::where('customer_account_id', $customerId)
            ->where('type', 'invoice')
            ->where('status', 'processed')
            ->get()
            ->map(function($invoice) {
                // ✅ Same balance calculation as CashbookController
                $receiptsPaid = Receipt::where('customer_id', $invoice->customer_account_id)
                    ->where('invoice_id', $invoice->id)
                    ->where('status', 'processed')
                    ->sum('total_amount');

                $cashbookPaid = CashbookEntry::where('reference_id', $invoice->id)
                    ->where('reference_type', 'invoice')
                    ->where('module', 'AR')
                    ->where('tr_code', 'Receipt')
                    ->sum('dr_amount');

                $totalPaid = $receiptsPaid + $cashbookPaid;
                $outstanding = max(0, $invoice->inclusive_total - $totalPaid);

                return [
                    'id'              => $invoice->id,
                    'document_number' => $invoice->document_number,
                    'inclusive_total' => $invoice->inclusive_total,
                    'outstanding'     => $outstanding,
                    'document_date'   => $invoice->document_date
                        ? $invoice->document_date->format('Y-m-d')
                        : null
                ];
            })
            ->filter(function($invoice) {
                return $invoice['outstanding'] > 0;
            })
            ->values();

        return response()->json($invoices);
    }
}
