<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\AccountTransaction;
use App\Models\FactoryInvoice;
use App\Models\PurchaseOrder;
use App\Models\Qc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class ManualTransactionController extends Controller
{
    /**
     * Display the manual transaction form
     */
    public function create(): View
    {
        // Get all active accounts that can be part of a manual transaction
        $accounts = Account::where('is_active', true)
            ->whereIn('model_type', ['contact', 'customer', 'supplier', 'employee', 'shop', 'user'])
            ->orderBy('name')
            ->get();

        // System accounts for the "other side" of the transaction
        $systemAccounts = Account::where('is_active', true)
            ->whereIn('name', ['Main Cash Account', 'Sales Revenue Control', 'Salary Expense Control'])
            ->get();

        return view('manual-transactions.create', compact('accounts', 'systemAccounts'));
    }

    /**
     * Store a new manual transaction (Double-Entry)
     */
    public function store(Request $request)
    {
        $request->validate([
            'account_id' => 'required|exists:accounts,id',
            'transaction_type' => 'required|in:receipt,payment',
            'amount' => 'required|numeric|min:0.01',
            'payment_method' => 'required|in:cash,bank,cheque',
            'reference_id' => 'nullable|integer',
            'reference_type' => 'nullable|string',
            'date' => 'required|date',
            'remarks' => 'nullable|string|max:1000',
        ]);

        DB::transaction(function () use ($request) {
            $account = Account::findOrFail($request->account_id);
            $amount = $request->amount;
            $cashAccount = Account::where('name', 'Main Cash Account')->first();
            
            if (!$cashAccount) {
                throw new \Exception("Main Cash Account not found. Please ensure system accounts are created.");
            }

            $referenceType = $request->reference_type;
            if ($referenceType && !str_contains($referenceType, '\\')) {
                $referenceType = "App\\Models\\" . $referenceType;
            }

            if ($request->transaction_type === 'receipt') {
                // Scenario: Customer/Shop pays us.
                // Debit: Cash (Asset increases)
                // Credit: Customer/Shop Account (Asset decreases / Receivable reduces)
                
                AccountTransaction::create([
                    'account_id' => $cashAccount->id,
                    'chart_of_account_id' => $cashAccount->chart_of_account_id,
                    'amount' => $amount,
                    'transaction_type' => 'debit',
                    'reference_id' => $request->reference_id,
                    'reference_type' => $referenceType,
                    'remarks' => "Receipt from {$account->name} - " . $request->remarks,
                    'created_at' => $request->date,
                ]);

                AccountTransaction::create([
                    'account_id' => $account->id,
                    'chart_of_account_id' => $account->chart_of_account_id,
                    'amount' => $amount,
                    'transaction_type' => 'credit',
                    'reference_id' => $request->reference_id,
                    'reference_type' => $referenceType,
                    'remarks' => "Payment received - " . $request->remarks,
                    'created_at' => $request->date,
                ]);

            } else {
                // Scenario: We pay Supplier/Employee.
                // Debit: Supplier/Employee Account (Liability decreases / Expense recorded)
                // Credit: Cash (Asset decreases)

                AccountTransaction::create([
                    'account_id' => $account->id,
                    'chart_of_account_id' => $account->chart_of_account_id,
                    'amount' => $amount,
                    'transaction_type' => 'debit',
                    'reference_id' => $request->reference_id,
                    'reference_type' => $referenceType,
                    'remarks' => "Payment to {$account->name} - " . $request->remarks,
                    'created_at' => $request->date,
                ]);

                AccountTransaction::create([
                    'account_id' => $cashAccount->id,
                    'chart_of_account_id' => $cashAccount->chart_of_account_id,
                    'amount' => $amount,
                    'transaction_type' => 'credit',
                    'reference_id' => $request->reference_id,
                    'reference_type' => $referenceType,
                    'remarks' => "Cash paid to {$account->name} - " . $request->remarks,
                    'created_at' => $request->date,
                ]);
            }
            
            // If it's a payment for a PO or Invoice, we could update its status here.
            $this->updateReferenceStatus($request->reference_id, $referenceType, $amount);
        });

        return redirect()->route('account-transactions.index')->with('success', 'Transaction processed successfully.');
    }

    /**
     * AJAX: Get pending documents for an account
     */
    public function getPendingDocuments(Request $request)
    {
        $accountId = $request->account_id;
        $account = Account::findOrFail($accountId);
        $documents = [];

        if (in_array($account->model_type, ['customer', 'shop'])) {
            // Get pending invoices
            $documents = FactoryInvoice::where('customer_account_id', $accountId)
                ->where('status', '!=', 'paid') // Assuming 'paid' is a status
                ->select('id', 'invoice_number as name', 'net_total as amount', 'created_at')
                ->get()
                ->map(function($doc) {
                    $doc->type = 'FactoryInvoice';
                    $doc->display_name = "Invoice: {$doc->name} - " . number_format($doc->amount, 2);
                    return $doc;
                });
        } elseif ($account->model_type === 'supplier') {
            // Get pending POs or QCs
            $documents = PurchaseOrder::where('contact_id', $account->model_id)
                ->where('status', '!=', 'completed')
                ->select('id', 'po_number as name', 'total_amount as amount', 'created_at')
                ->get()
                ->map(function($doc) {
                    $doc->type = 'PurchaseOrder';
                    $doc->display_name = "PO: {$doc->name} - " . number_format($doc->amount, 2);
                    return $doc;
                });
        }

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

    private function updateReferenceStatus($id, $type, $amount)
    {
        if (!$id || !$type) return;

        if ($type === 'App\\Models\\FactoryInvoice') {
            $invoice = FactoryInvoice::find($id);
            if ($invoice) {
                // Check if total paid >= net_total
                // Need a way to track total paid on invoice
            }
        } elseif ($type === 'App\\Models\\PurchaseOrder') {
            $po = PurchaseOrder::find($id);
            if ($po) {
                // Update PO payment status
            }
        }
    }
}
