<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';
include '../includes/accounting_posting.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT', 'FINANCE_MANAGER', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles, true)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$debtor_id = (int)($_POST['debtor_id'] ?? 0);
$receivable_account_id = (int)($_POST['receivable_account_id'] ?? 0);
$bank_account_id = (int)($_POST['bank_account_id'] ?? 0);
$amount = round((float)($_POST['amount'] ?? 0), 2);
$entry_date = trim((string)($_POST['entry_date'] ?? date('Y-m-d')));
$description = trim((string)($_POST['description'] ?? 'AR reconciliation receipt'));
$reference = trim((string)($_POST['reference'] ?? ''));

if ($debtor_id <= 0 || $receivable_account_id <= 0 || $bank_account_id <= 0 || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Debtor, receivable account, bank account and valid amount are required.']);
    exit();
}

$conn->begin_transaction();
try {
    accEnsureReconciliationAccounts($conn);

    $d = $conn->prepare("SELECT debtor_name, current_balance FROM debtors WHERE debtor_id=? LIMIT 1");
    $d->bind_param('i', $debtor_id);
    $d->execute();
    $debtor = $d->get_result()->fetch_assoc();
    $d->close();
    if (!$debtor) throw new Exception('Debtor not found.');
    if ((float)$debtor['current_balance'] < $amount) throw new Exception('Receipt exceeds debtor outstanding balance.');

    $r = $conn->prepare("SELECT account_id FROM chart_of_accounts WHERE account_id=? AND account_type='ASSET' AND is_active=1 LIMIT 1");
    $r->bind_param('i', $receivable_account_id);
    $r->execute();
    $recOk = $r->get_result()->fetch_assoc();
    $r->close();
    if (!$recOk) throw new Exception('Receivable account must be an active asset account.');

    $b = $conn->prepare("SELECT account_id FROM chart_of_accounts WHERE account_id=? AND account_type='ASSET' AND is_active=1 LIMIT 1");
    $b->bind_param('i', $bank_account_id);
    $b->execute();
    $bankOk = $b->get_result()->fetch_assoc();
    $b->close();
    if (!$bankOk) throw new Exception('Bank/Cash/MPESA account must be an active asset account.');

    $lineSeed = [
        ['account_id' => $bank_account_id],
        ['account_id' => $receivable_account_id],
    ];
    $desc = '[PAYMENT] ' . $description . ($reference !== '' ? ' (Ref: '.$reference.')' : '');
    $prefix = accClassifyPostingPrefix($conn, $lineSeed, $desc);
    $journal_number = accGenerateJournalNumberByPrefix($conn, $prefix);
    $fiscal_year = (int)date('Y', strtotime($entry_date));
    $fiscal_period = (int)date('n', strtotime($entry_date));
    $created_by = (int)$_SESSION['user_id'];
    $notes = 'AR bank reconciliation allocation';

    $je = $conn->prepare("INSERT INTO journal_entries
        (journal_number, entry_date, entry_type, reference_type, reference_id, description, total_debit, total_credit, status, fiscal_year, fiscal_period, notes, created_by)
        VALUES (?, ?, 'MANUAL', 'GENERAL', ?, ?, ?, ?, 'POSTED', ?, ?, ?, ?)");
    $je->bind_param('ssisddiisi', $journal_number, $entry_date, $debtor_id, $desc, $amount, $amount, $fiscal_year, $fiscal_period, $notes, $created_by);
    if (!$je->execute()) throw new Exception($je->error);
    $journal_id = (int)$conn->insert_id;
    $je->close();

    $jl = $conn->prepare("INSERT INTO journal_entry_lines (journal_id, line_number, account_id, debit_amount, credit_amount, description)
                          VALUES (?, ?, ?, ?, ?, ?)");
    $zero = 0.0;
    $line1 = 1;
    $line2 = 2;
    $jl->bind_param('iiidds', $journal_id, $line1, $bank_account_id, $amount, $zero, $desc);
    if (!$jl->execute()) throw new Exception($jl->error);
    $jl->bind_param('iiidds', $journal_id, $line2, $receivable_account_id, $zero, $amount, $desc);
    if (!$jl->execute()) throw new Exception($jl->error);
    $jl->close();

    $post = $conn->prepare("CALL PostJournalToLedger(?)");
    $post->bind_param('i', $journal_id);
    if (!$post->execute()) throw new Exception('Failed to post journal to ledger: '.$post->error);
    $post->close();
    while ($conn->more_results()) {
        $conn->next_result();
        if ($res = $conn->store_result()) $res->free();
    }

    $du = $conn->prepare("UPDATE debtors SET current_balance=current_balance-? WHERE debtor_id=?");
    $du->bind_param('di', $amount, $debtor_id);
    if (!$du->execute()) throw new Exception($du->error);
    $du->close();

    $conn->query("CREATE TABLE IF NOT EXISTS ar_reconciliation_matches (
        match_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        debtor_id INT NOT NULL,
        journal_id INT NOT NULL,
        receivable_account_id INT NOT NULL,
        bank_account_id INT NOT NULL,
        amount DECIMAL(15,2) NOT NULL,
        reference VARCHAR(100) NULL,
        created_by INT NOT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $rm = $conn->prepare("INSERT INTO ar_reconciliation_matches
        (debtor_id, journal_id, receivable_account_id, bank_account_id, amount, reference, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?)");
    $rm->bind_param('iiiidsi', $debtor_id, $journal_id, $receivable_account_id, $bank_account_id, $amount, $reference, $created_by);
    $rm->execute();
    $rm->close();

    $conn->commit();
    echo json_encode([
        'success' => true,
        'message' => 'AR receipt allocated to debtor successfully.',
        'journal_number' => $journal_number,
        'posting_prefix' => $prefix
    ]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit();
