<?php
// Business logic (including any header('Location: ...') redirects after a POST action)
// must run before includes/header.php, since that include emits HTML immediately and
// would make any later redirect fail silently ("headers already sent"), leaving the
// page blank after actions like recording a payment.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/CreditSales.php';
require_once __DIR__ . '/../../includes/payment_options.php';

$database = new Database();
$conn     = $database->getConnection();
$auth     = new Auth($conn);
$auth->requireLogin();

$creditSales  = new CreditSales($conn);
$userId       = (int)$_SESSION['user_id'];
$role         = strtolower((string)($_SESSION['role'] ?? ''));
$isController = in_array($role, ['controller'], true) || $auth->isController($userId);
$isStrictAdmin = in_array($role, ['admin', 'super_admin'], true) || $auth->isSuperAdmin($userId);
$isAdminLike  = $isController || $isStrictAdmin;
$branchId     = $isAdminLike ? null : (int)$auth->getUserBranch($userId);
$error        = '';
$success      = $_GET['success'] ?? '';

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';

        if ($action === 'add_payment') {
            if ($isController) throw new RuntimeException('Controllers cannot record payments on credit sales.');
            $credit = $creditSales->getCreditById((int)$_POST['credit_id']);
            if (!$credit) throw new RuntimeException('Credit sale not found.');
            if (!$isAdminLike && (int)$credit['branch_id'] !== (int)$branchId)
                throw new RuntimeException('You cannot update another branch credit sale.');
            if (($credit['status'] ?? '') !== 'approved')
                throw new RuntimeException('Controller approval is required before payments can be posted.');
            $paymentMethod = $_POST['payment_method'] ?? 'cash';
            $paymentId = $creditSales->recordPayment((int)$credit['credit_id'], (float)$_POST['amount'], $paymentMethod, $_POST['notes'] ?? '', $userId);
            $updatedCredit = $creditSales->getCreditById((int)$credit['credit_id']);
            if ($updatedCredit && (float)$updatedCredit['balance'] <= 0 && ($updatedCredit['status'] ?? '') === 'completed') {
                try {
                    $creditSales->prepareFinalEisReceipt((int)$updatedCredit['credit_id'], $userId, $paymentMethod);
                } catch (Throwable $e) {
                    error_log('Credit sale final EIS receipt failed for credit #' . (int)$updatedCredit['credit_id'] . ': ' . $e->getMessage());
                }
            }
            header('Location: credit_receipt.php?credit_id=' . (int)$credit['credit_id'] . '&payment_id=' . (int)$paymentId);
            exit();

        } elseif ($action === 'edit_credit') {
            $credit = $creditSales->getCreditById((int)$_POST['credit_id']);
            if (!$credit) throw new RuntimeException('Credit account not found.');
            if (!$isAdminLike && (int)$credit['branch_id'] !== (int)$branchId)
                throw new RuntimeException('You cannot edit another branch credit sale.');
            $creditSales->updateCredit((int)$credit['credit_id'], [
                'customer_name'  => $_POST['customer_name'] ?? '',
                'customer_phone' => $_POST['customer_phone'] ?? '',
                'total_amount'   => (isset($_POST['total_amount']) && $_POST['total_amount'] !== '') ? $_POST['total_amount'] : null,
                'items'          => json_decode((string)($_POST['items_json'] ?? ''), true) ?: [],
            ]);
            $success = 'Credit sale updated.';

        } elseif ($action === 'delete_credit') {
            // Admin/super_admin only — pending accounts with no payments
            if (!$isStrictAdmin) throw new RuntimeException('Only administrators can use this delete action.');
            $credit = $creditSales->getCreditById((int)$_POST['credit_id']);
            if (!$credit) throw new RuntimeException('Credit account not found.');
            $creditSales->deleteCredit((int)$credit['credit_id'], $userId, $_POST['delete_notes'] ?? '');
            $success = 'Credit sale deleted and items returned to shelf.';

        } elseif ($action === 'controller_delete_credit') {
            // Controller only — any status, full audit trail
            if (!$isController) throw new RuntimeException('Only controllers can use this action.');
            $credit = $creditSales->getCreditById((int)$_POST['credit_id']);
            if (!$credit) throw new RuntimeException('Credit account not found.');
            $creditSales->controllerDeleteCredit((int)$credit['credit_id'], $userId, $_POST['delete_notes'] ?? '');
            $success = 'Credit sale deleted. Items returned to shelf and deletion recorded for audit.';

        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$activeStatus   = $_GET['status'] ?? '';
$deletedCredits = $creditSales->getDeletedCredits($branchId, 100);
$credits        = ($activeStatus === 'deleted') ? [] : $creditSales->getCredits($branchId, $activeStatus ?: null, 300);
$summary        = $creditSales->getSummary($branchId);

// Per-status counts for tabs
$scStmt = $conn->prepare(
    "SELECT status, COUNT(*) AS cnt FROM credit_accounts"
    . ($branchId ? " WHERE branch_id = :b" : "")
    . " GROUP BY status"
);
$scStmt->execute($branchId ? [':b' => (int)$branchId] : []);
$statusCounts = ['pending_controller_approval' => 0, 'approved' => 0, 'rejected' => 0, 'completed' => 0, 'deleted' => 0];
foreach ($scStmt->fetchAll(PDO::FETCH_ASSOC) as $sc) {
    $statusCounts[$sc['status']] = (int)$sc['cnt'];
}
$statusCounts['deleted'] = count($deletedCredits);
$statusCounts[''] = array_sum(array_diff_key($statusCounts, ['deleted' => 0]));

// Batch-fetch sold items
$itemsByCredit = [];
$creditIds = array_column($credits, 'credit_id');
if (!empty($creditIds)) {
    $inClause  = implode(',', array_map('intval', $creditIds));
    $iStmt = $conn->query("SELECT id, credit_id, item_name, unique_code, unit_price FROM credit_sale_items WHERE credit_id IN ($inClause) ORDER BY id ASC");
    foreach ($iStmt->fetchAll(PDO::FETCH_ASSOC) as $iRow) {
        $itemsByCredit[(int)$iRow['credit_id']][] = $iRow;
    }
}

// Payable credits for the payment section (approved, balance > 0)
$payableCredits = [];
if ($activeStatus !== 'deleted') {
    foreach ($creditSales->getCredits($branchId, 'approved', 500) as $ac) {
        if ((float)$ac['balance'] > 0) {
            $payableCredits[] = $ac;
        }
    }
}
// Batch-fetch items for payable credits
$payableItemsByCredit = [];
$payableCreditIds = array_column($payableCredits, 'credit_id');
if (!empty($payableCreditIds)) {
    $piClause = implode(',', array_map('intval', $payableCreditIds));
    $piStmt   = $conn->query("SELECT credit_id, item_name, unique_code, unit_price FROM credit_sale_items WHERE credit_id IN ($piClause) ORDER BY id ASC");
    foreach ($piStmt->fetchAll(PDO::FETCH_ASSOC) as $piRow) {
        $payableItemsByCredit[(int)$piRow['credit_id']][] = $piRow;
    }
}

$statusBadgeMap = ['pending_controller_approval' => 'warning', 'approved' => 'success', 'rejected' => 'danger', 'completed' => 'dark'];
$statusTabs     = [
    ''                            => ['label' => 'All',       'badge' => 'secondary'],
    'pending_controller_approval' => ['label' => 'Pending',   'badge' => 'warning'],
    'approved'                    => ['label' => 'Approved',  'badge' => 'success'],
    'rejected'                    => ['label' => 'Rejected',  'badge' => 'danger'],
    'completed'                   => ['label' => 'Completed', 'badge' => 'dark'],
    'deleted'                     => ['label' => 'Deleted Credit Sales', 'badge' => 'danger'],
];

$payableCreditsJson = [];
foreach ($payableCredits as $pc) {
    $pcItems = $payableItemsByCredit[(int)$pc['credit_id']] ?? [];
    $payableCreditsJson[(int)$pc['credit_id']] = [
        'credit_id' => (int)$pc['credit_id'],
        'credit_number' => (string)$pc['credit_number'],
        'customer_name' => (string)$pc['customer_name'],
        'customer_phone' => (string)($pc['customer_phone'] ?? ''),
        'total_amount' => (float)$pc['total_amount'],
        'amount_paid' => (float)$pc['amount_paid'],
        'balance' => (float)$pc['balance'],
        'items' => array_map(static function ($item) {
            return [
                'item_name' => (string)($item['item_name'] ?? ''),
                'unique_code' => (string)$item['unique_code'],
                'unit_price' => (float)$item['unit_price'],
            ];
        }, $pcItems),
    ];
}

include '../../includes/header.php';
?>
<style>
    .credit-items-row td { background:#F8FAFC; padding:0!important; }
    .credit-items-inner { padding:10px 16px; border-top:2px solid #4F46E5; }
    .credit-items-inner .table { margin:0; font-size:.82rem; }
    .credit-items-inner .table thead th { background:#1E293B; color:#fff; font-size:.72rem; font-weight:600; letter-spacing:.04em; border:none; }
    .credit-items-inner .items-title { font-size:.75rem; font-weight:700; color:#4F46E5; text-transform:uppercase; letter-spacing:.06em; margin-bottom:8px; display:flex; align-items:center; gap:6px; }
    .toggle-items-btn { font-size:.72rem; padding:2px 8px; }
    .toggle-items-btn.active { background:#4F46E5; color:#fff; border-color:#4F46E5; }
    .section-heading { font-size:1rem; font-weight:700; color:#1E293B; border-left:4px solid #4F46E5; padding-left:10px; }
    .income-form-card { background:#F8FAFC; border:1px solid #E2E8F0; border-radius:8px; padding:18px; }
    .deleted-row td { background:#fff5f5; }
</style>

<div class="container-fluid px-4 mt-4">
    <div class="mb-3">
        <h1>Debtors</h1>
        <p class="text-muted mb-0">Credit sales, payments and controller approvals.</p>
    </div>

    <?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <?php echo htmlspecialchars($success); ?>
    </div>
    <?php endif; ?>
    <?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>

    <!-- Summary -->
    <div class="row mb-4">
        <div class="col-md-3"><div class="card"><div class="card-body py-3"><div class="text-muted small">Total Accounts</div><h4 class="mb-0"><?php echo (int)$summary['total_accounts']; ?></h4></div></div></div>
        <div class="col-md-3"><div class="card"><div class="card-body py-3"><div class="text-muted small">Credit Value</div><h4 class="mb-0">MWK <?php echo number_format((float)$summary['total_credit'], 2); ?></h4></div></div></div>
        <div class="col-md-3"><div class="card"><div class="card-body py-3"><div class="text-muted small">Collected</div><h4 class="mb-0">MWK <?php echo number_format((float)$summary['total_paid'], 2); ?></h4></div></div></div>
        <div class="col-md-3"><div class="card border-danger"><div class="card-body py-3"><div class="text-muted small">Outstanding Balance</div><h4 class="mb-0 text-danger">MWK <?php echo number_format((float)$summary['outstanding_balance'], 2); ?></h4></div></div></div>
    </div>

    <!-- ═══════════════════════
         CREDIT SALES TABLE
    ═══════════════════════ -->
    <div class="card mb-4">
        <div class="card-header"><span class="section-heading">Credit Sales</span></div>
        <div class="card-body pb-1">

            <ul class="nav nav-tabs mb-3">
                <?php foreach ($statusTabs as $key => $tab): ?>
                <li class="nav-item">
                    <a class="nav-link <?php echo $activeStatus === $key ? 'active' : ''; ?>"
                       href="?status=<?php echo urlencode($key); ?>">
                        <?php echo $tab['label']; ?>
                        <span class="badge bg-<?php echo $tab['badge']; ?> ms-1"><?php echo $statusCounts[$key] ?? 0; ?></span>
                    </a>
                </li>
                <?php endforeach; ?>
            </ul>

            <?php if ($activeStatus === 'deleted'): ?>
            <div class="table-responsive">
                <table class="table table-bordered table-sm">
                    <thead class="table-dark">
                        <tr>
                            <th>Deleted At</th>
                            <?php if ($isAdminLike): ?><th>Branch</th><?php endif; ?>
                            <th>Credit No.</th>
                            <th>Customer</th>
                            <th>Total</th>
                            <th>Was Paid</th>
                            <th>Balance</th>
                            <th>Status When Deleted</th>
                            <th>Items Returned</th>
                            <th>Reason / Notes</th>
                            <th>Deleted By</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($deletedCredits as $dr):
                        $drItems = json_decode((string)($dr['items_json'] ?? '[]'), true) ?: [];
                    ?>
                    <tr class="deleted-row">
                        <td style="white-space:nowrap;font-size:.8rem;">
                            <?php echo date('d M Y', strtotime($dr['deleted_at'])); ?><br>
                            <small class="text-muted"><?php echo date('H:i', strtotime($dr['deleted_at'])); ?></small>
                        </td>
                        <?php if ($isAdminLike): ?>
                        <td><?php echo htmlspecialchars($dr['branch_name'] ?? '—'); ?></td>
                        <?php endif; ?>
                        <td><code><?php echo htmlspecialchars($dr['credit_number']); ?></code></td>
                        <td>
                            <?php echo htmlspecialchars($dr['customer_name']); ?>
                            <?php if (!empty($dr['customer_phone'])): ?>
                            <br><small class="text-muted"><?php echo htmlspecialchars($dr['customer_phone']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td>MWK <?php echo number_format((float)$dr['total_amount'], 2); ?></td>
                        <td>MWK <?php echo number_format((float)$dr['amount_paid'], 2); ?></td>
                        <td class="<?php echo (float)$dr['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                            MWK <?php echo number_format((float)$dr['balance'], 2); ?>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $statusBadgeMap[$dr['status_at_deletion']] ?? 'secondary'; ?>">
                                <?php echo ucwords(str_replace('_', ' ', $dr['status_at_deletion'])); ?>
                            </span>
                        </td>
                        <td class="text-center">
                            <span class="badge bg-success">
                                <i class="fas fa-check me-1"></i><?php echo count($drItems); ?> item<?php echo count($drItems) !== 1 ? 's' : ''; ?>
                            </span>
                        </td>
                        <td>
                            <?php if (!empty($dr['deletion_notes'])): ?>
                            <span title="<?php echo htmlspecialchars($dr['deletion_notes']); ?>">
                                <?php echo htmlspecialchars(mb_strimwidth($dr['deletion_notes'], 0, 60, '…')); ?>
                            </span>
                            <?php else: ?>
                            <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td><small><?php echo htmlspecialchars($dr['deleted_by_name'] ?? '—'); ?></small></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (!$deletedCredits): ?>
                        <tr><td colspan="<?php echo $isAdminLike ? 11 : 10; ?>" class="text-center text-muted py-4"><i class="fas fa-check-circle text-success me-1"></i> No deleted credit sales on record.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table table-bordered table-sm">
                    <thead>
                        <tr>
                            <th>Credit No.</th>
                            <th>Branch</th>
                            <th>Customer</th>
                            <th>Total</th>
                            <th>Paid</th>
                            <th>Balance</th>
                            <th>Status</th>
                            <th>Items</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($credits as $credit):
                        $creditItems   = $itemsByCredit[(int)$credit['credit_id']] ?? [];
                        $itemCount     = count($creditItems);
                        $cStatus       = $credit['status'] ?? 'pending_controller_approval';
                        $isPending     = $cStatus === 'pending_controller_approval';
                        $hasNoPayments = (float)$credit['amount_paid'] == 0;
                        $isOwnBranch   = $isAdminLike || ((int)$credit['branch_id'] === (int)$branchId);
                        $canEdit       = $isOwnBranch;
                        $canAdminDelete = $isStrictAdmin && $isPending && $hasNoPayments;
                        $canControllerDelete = $isController;
                    ?>
                        <tr>
                            <td><?php echo htmlspecialchars($credit['credit_number']); ?></td>
                            <td><?php echo htmlspecialchars($credit['branch_name'] ?? $credit['branch_id']); ?></td>
                            <td>
                                <?php echo htmlspecialchars($credit['customer_name']); ?>
                                <?php if (!empty($credit['customer_phone'])): ?>
                                <br><small class="text-muted"><?php echo htmlspecialchars($credit['customer_phone']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>MWK <?php echo number_format((float)$credit['total_amount'], 2); ?></td>
                            <td>MWK <?php echo number_format((float)$credit['amount_paid'], 2); ?></td>
                            <td class="<?php echo (float)$credit['balance'] > 0 ? 'text-danger fw-bold' : 'text-success'; ?>">
                                MWK <?php echo number_format((float)$credit['balance'], 2); ?>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo $statusBadgeMap[$cStatus] ?? 'secondary'; ?>">
                                    <?php echo ucwords(str_replace('_', ' ', $cStatus)); ?>
                                </span>
                            </td>
                            <td class="text-center">
                                <?php if ($itemCount > 0): ?>
                                <button type="button" class="btn btn-sm btn-outline-primary toggle-items-btn"
                                        data-target="#credit-items-<?php echo (int)$credit['credit_id']; ?>">
                                    <i class="fas fa-box"></i> <?php echo $itemCount; ?> item<?php echo $itemCount !== 1 ? 's' : ''; ?>
                                </button>
                                <?php else: ?><span class="text-muted" style="font-size:.75rem;">—</span><?php endif; ?>
                            </td>
                            <td style="min-width:200px;">
                                <a class="btn btn-sm btn-outline-secondary mb-1"
                                   href="credit_receipt.php?credit_id=<?php echo (int)$credit['credit_id']; ?>">
                                    <i class="fas fa-eye"></i> View
                                </a>

                                <?php if ($canEdit): ?>
                                <button type="button" class="btn btn-sm btn-outline-warning mb-1 edit-credit-btn"
                                    data-credit-id="<?php echo (int)$credit['credit_id']; ?>"
                                    data-credit-number="<?php echo htmlspecialchars($credit['credit_number'], ENT_QUOTES); ?>"
                                    data-customer-name="<?php echo htmlspecialchars($credit['customer_name'], ENT_QUOTES); ?>"
                                    data-customer-phone="<?php echo htmlspecialchars($credit['customer_phone'] ?? '', ENT_QUOTES); ?>"
                                    data-total-amount="<?php echo (float)$credit['total_amount']; ?>"
                                    data-amount-paid="<?php echo (float)$credit['amount_paid']; ?>"
                                    data-status="<?php echo htmlspecialchars($cStatus, ENT_QUOTES); ?>"
                                    data-items="<?php echo htmlspecialchars(json_encode(array_values($creditItems)), ENT_QUOTES); ?>">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <?php endif; ?>

                                <?php if ($canAdminDelete): ?>
                                <button type="button" class="btn btn-sm btn-outline-danger mb-1 delete-credit-btn"
                                    data-action="delete_credit"
                                    data-credit-id="<?php echo (int)$credit['credit_id']; ?>"
                                    data-credit-number="<?php echo htmlspecialchars($credit['credit_number'], ENT_QUOTES); ?>"
                                    data-customer-name="<?php echo htmlspecialchars($credit['customer_name'], ENT_QUOTES); ?>">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                                <?php endif; ?>

                                <?php if ($canControllerDelete): ?>
                                <button type="button" class="btn btn-sm btn-danger mb-1 delete-credit-btn"
                                    data-action="controller_delete_credit"
                                    data-credit-id="<?php echo (int)$credit['credit_id']; ?>"
                                    data-credit-number="<?php echo htmlspecialchars($credit['credit_number'], ENT_QUOTES); ?>"
                                    data-customer-name="<?php echo htmlspecialchars($credit['customer_name'], ENT_QUOTES); ?>">
                                    <i class="fas fa-trash-alt"></i> Delete &amp; Return Stock
                                </button>
                                <?php endif; ?>

                                <?php if ($isPending && in_array($role, ['controller', 'admin', 'super_admin'], true)): ?>
                                <div class="mt-2 pt-2 border-top d-flex">
                                    <form method="post" action="../dashboard/controller_action.php" class="me-1">
                                        <input type="hidden" name="action" value="credit_status">
                                        <input type="hidden" name="credit_id" value="<?php echo (int)$credit['credit_id']; ?>">
                                        <button name="status" value="approved" class="btn btn-sm btn-success">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                    </form>
                                    <form method="post" action="../dashboard/controller_action.php">
                                        <input type="hidden" name="action" value="credit_status">
                                        <input type="hidden" name="credit_id" value="<?php echo (int)$credit['credit_id']; ?>">
                                        <button name="status" value="rejected" class="btn btn-sm btn-outline-danger">
                                            <i class="fas fa-times"></i> Reject
                                        </button>
                                    </form>
                                </div>
                                <?php endif; ?>
                            </td>
                        </tr>

                        <?php if ($itemCount > 0): ?>
                        <tr class="credit-items-row d-none" id="credit-items-<?php echo (int)$credit['credit_id']; ?>">
                            <td colspan="9">
                                <div class="credit-items-inner">
                                    <div class="items-title">
                                        <i class="fas fa-box-open"></i>
                                        Sold Items — <?php echo htmlspecialchars($credit['customer_name']); ?>
                                        <span class="badge bg-primary"><?php echo $itemCount; ?></span>
                                    </div>
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead><tr><th>#</th><th>Item Name</th><th>Unique Code</th><th class="text-end">Unit Price (MWK)</th></tr></thead>
                                        <tbody>
                                            <?php foreach ($creditItems as $idx => $item): ?>
                                            <tr>
                                                <td><?php echo $idx + 1; ?></td>
                                                <td><?php echo htmlspecialchars($item['item_name'] ?? '—'); ?></td>
                                                <td><code><?php echo htmlspecialchars($item['unique_code']); ?></code></td>
                                                <td class="text-end"><?php echo number_format((float)$item['unit_price'], 2); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="3" class="text-end fw-bold">Total</td>
                                                <td class="text-end fw-bold">MWK <?php echo number_format(array_sum(array_column($creditItems, 'unit_price')), 2); ?></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </td>
                        </tr>
                        <?php endif; ?>

                    <?php endforeach; ?>
                    <?php if (!$credits): ?>
                        <tr><td colspan="9" class="text-center text-muted py-4">No credit sales found for this filter.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════════════════
         PAYMENT SECTION
    ═══════════════════════ -->
    <?php if (!$isController): ?>
    <div class="card mb-4" id="paymentSectionCard">
        <div class="card-header">
            <span class="section-heading" style="border-left-color:#10B981;">
                <i class="fas fa-money-bill-wave me-2"></i>Record Payment
            </span>
        </div>
        <div class="card-body">
            <?php if (empty($payableCredits)): ?>
            <p class="text-muted mb-0"><i class="fas fa-info-circle me-1"></i> No approved credit sales with an outstanding balance.</p>
            <?php else: ?>
            <div class="row mb-3">
                <div class="col-lg-6">
                    <label class="fw-bold mb-1">Select Credit Sale <span class="text-danger">*</span></label>
                    <select id="paymentCreditSelect" class="form-control">
                        <option value="">— Choose a credit sale —</option>
                        <?php foreach ($payableCredits as $pc): ?>
                        <option value="<?php echo (int)$pc['credit_id']; ?>">
                            <?php echo htmlspecialchars($pc['credit_number']); ?> &mdash; <?php echo htmlspecialchars($pc['customer_name']); ?> &mdash; Balance: MWK <?php echo number_format((float)$pc['balance'], 2); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div id="paymentDetailPanel" style="display:none;">
                <div class="row mb-3">
                    <div class="col-md-4">
                        <div class="p-3 bg-light rounded">
                            <div class="small text-muted fw-bold text-uppercase mb-1">Customer</div>
                            <div class="fw-bold" id="pdCustomer"></div>
                            <div class="small text-muted" id="pdPhone"></div>
                        </div>
                    </div>
                    <div class="col-md-2 mt-2 mt-md-0">
                        <div class="p-3 bg-light rounded text-center">
                            <div class="small text-muted fw-bold text-uppercase mb-1">Total</div>
                            <div class="fw-bold" id="pdTotal"></div>
                        </div>
                    </div>
                    <div class="col-md-2 mt-2 mt-md-0">
                        <div class="p-3 bg-light rounded text-center">
                            <div class="small text-muted fw-bold text-uppercase mb-1">Paid</div>
                            <div class="fw-bold text-success" id="pdPaid"></div>
                        </div>
                    </div>
                    <div class="col-md-3 mt-2 mt-md-0">
                        <div class="p-3 rounded text-center border border-danger">
                            <div class="small text-muted fw-bold text-uppercase mb-1">Balance Due</div>
                            <div class="fw-bold text-danger" id="pdBalance"></div>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <div class="small fw-bold text-muted text-uppercase mb-1" style="letter-spacing:.05em;">Items on Credit</div>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-0">
                            <thead class="table-light">
                                <tr><th>#</th><th>Item</th><th>Code</th><th class="text-end">Unit Price (MWK)</th></tr>
                            </thead>
                            <tbody id="pdItemsBody"></tbody>
                        </table>
                    </div>
                </div>

                <form method="post" id="paymentForm">
                    <input type="hidden" name="action" value="add_payment">
                    <input type="hidden" name="credit_id" id="paymentCreditId">
                    <div class="row align-items-end">
                        <div class="col-md-3 mb-2">
                            <label class="fw-bold">Amount (MWK) <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" min="0.01" name="amount" id="paymentAmount"
                                   class="form-control" placeholder="0.00" required>
                            <small class="text-muted" id="pdMaxHint"></small>
                        </div>
                        <div class="col-md-3 mb-2">
                            <label class="fw-bold">Payment Method <span class="text-danger">*</span></label>
                            <select name="payment_method" class="form-control">
                                <?php echo paymentMethodSelectOptions('cash'); ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-2">
                            <label class="fw-bold">Notes</label>
                            <input type="text" name="notes" class="form-control" placeholder="Optional notes">
                        </div>
                        <div class="col-md-2 mb-2">
                            <button type="submit" class="btn btn-success btn-block">
                                <i class="fas fa-money-bill me-1"></i> Record Payment
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

</div>

<!-- Edit Credit Modal -->
<div class="modal fade" id="editCreditModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-edit me-1"></i> Edit Credit Sale &mdash; <span id="editCreditNumber" class="text-muted fw-normal"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="editCreditForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit_credit">
                    <input type="hidden" name="credit_id" id="editCreditId">
                    <input type="hidden" name="items_json" id="editItemsJson">

                    <!-- Customer Details -->
                    <h6 class="fw-bold text-uppercase text-muted mb-2" style="font-size:.72rem;letter-spacing:.06em;border-bottom:1px solid #E2E8F0;padding-bottom:6px;">
                        <i class="fas fa-user me-1"></i> Customer Details
                    </h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="fw-bold">Customer Name <span class="text-danger">*</span></label>
                                <input type="text" name="customer_name" id="editCustomerName" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="fw-bold">Customer Phone</label>
                                <input type="text" name="customer_phone" id="editCustomerPhone" class="form-control">
                            </div>
                        </div>
                    </div>

                    <!-- Items -->
                    <h6 class="fw-bold text-uppercase text-muted mb-2 mt-3" style="font-size:.72rem;letter-spacing:.06em;border-bottom:1px solid #E2E8F0;padding-bottom:6px;">
                        <i class="fas fa-box-open me-1"></i> Items Sold
                    </h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-1">
                            <thead class="table-light">
                                <tr><th style="width:32px">#</th><th>Item Name</th><th>Code</th><th style="width:160px">Unit Price (MWK)</th></tr>
                            </thead>
                            <tbody id="editItemsBody">
                                <tr><td colspan="4" class="text-center text-muted">No items.</td></tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="3" class="text-end fw-bold">Calculated Total:</td>
                                    <td class="fw-bold text-primary" id="editItemsCalcTotal">MWK 0.00</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <small class="text-muted" id="editItemsNote"></small>

                    <!-- Total override (pending + no payments only) -->
                    <div class="form-group mt-3" id="editTotalGroup" style="display:none;">
                        <label class="fw-bold">Override Total Amount (MWK)</label>
                        <input type="number" step="0.01" min="0.01" name="total_amount" id="editTotalAmount" class="form-control" style="max-width:220px;">
                        <small class="text-muted">Leave blank to use the calculated total from item prices above.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning"><i class="fas fa-save me-1"></i> Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete / Controller Delete Modal -->
<div class="modal fade" id="deleteCreditModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-trash-alt me-1"></i> Delete Credit Sale</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="deleteCreditForm">
                <div class="modal-body">
                    <input type="hidden" name="action" id="deleteCreditAction" value="delete_credit">
                    <input type="hidden" name="credit_id" id="deleteCreditId">
                    <p>Delete credit sale <strong id="deleteCreditNumber"></strong> for <strong id="deleteCustomerName"></strong>?</p>
                    <div class="alert alert-warning mb-3" id="deleteStockNote">
                        <i class="fas fa-undo me-1"></i>
                        All sold items on this credit sale will be <strong>returned to shelf</strong> (made available for re-sale).
                        This action is <strong>permanently recorded</strong> for audit.
                    </div>
                    <div class="form-group mb-0">
                        <label class="fw-bold">Reason / Notes <span class="text-danger">*</span></label>
                        <textarea name="delete_notes" id="deleteNotes" class="form-control" rows="3"
                                  placeholder="Explain why this credit sale is being deleted..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash-alt me-1"></i> Confirm Delete
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).on('click', '.toggle-items-btn', function () {
    var target = $($(this).data('target'));
    target.toggleClass('d-none');
    $(this).toggleClass('active');
    $(this).find('i').toggleClass('fa-box fa-box-open');
});

function crEditCalcTotal() {
    var sum = 0;
    $('.edit-item-price').each(function () { sum += parseFloat($(this).val()) || 0; });
    $('#editItemsCalcTotal').text('MWK ' + sum.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
    var items = [];
    $('.edit-item-price').each(function () {
        items.push({ id: parseInt($(this).data('item-id'), 10), unit_price: parseFloat($(this).val()) || 0 });
    });
    $('#editItemsJson').val(JSON.stringify(items));
}

$(document).on('input', '.edit-item-price', crEditCalcTotal);

$(document).on('click', '.edit-credit-btn', function () {
    var btn      = $(this);
    var status   = btn.data('status');
    var paid     = parseFloat(btn.data('amount-paid')) || 0;
    var canEdit  = status === 'pending_controller_approval' && paid === 0;
    var items    = btn.data('items') || [];

    $('#editCreditId').val(btn.data('credit-id'));
    $('#editCreditNumber').text(btn.data('credit-number') || '');
    $('#editCustomerName').val(btn.data('customer-name'));
    $('#editCustomerPhone').val(btn.data('customer-phone'));
    $('#editItemsJson').val('[]');

    // Build items table
    var rows = '';
    (Array.isArray(items) ? items : []).forEach(function (item, idx) {
        var priceCell = canEdit
            ? '<input type="number" step="0.01" min="0.01" class="form-control form-control-sm edit-item-price" '
                + 'value="' + parseFloat(item.unit_price || 0).toFixed(2) + '" '
                + 'data-item-id="' + parseInt(item.id, 10) + '">'
            : 'MWK ' + parseFloat(item.unit_price || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        rows += '<tr>'
            + '<td>' + (idx + 1) + '</td>'
            + '<td>' + escapeHtml(item.item_name || '-') + '</td>'
            + '<td><code>' + escapeHtml(item.unique_code || '') + '</code></td>'
            + '<td>' + priceCell + '</td>'
            + '</tr>';
    });
    $('#editItemsBody').html(rows || '<tr><td colspan="4" class="text-center text-muted">No items on this credit sale.</td></tr>');

    // Note and total-override field
    if (canEdit) {
        $('#editItemsNote').html('<i class="fas fa-info-circle text-primary me-1"></i>Edit unit prices above. The total will be recalculated automatically on save.');
        $('#editTotalAmount').val('');
        $('#editTotalGroup').show();
    } else {
        $('#editItemsNote').html('<i class="fas fa-lock text-muted me-1"></i>Item prices cannot be changed after the sale is approved or a payment has been recorded.');
        $('#editTotalAmount').val('');
        $('#editTotalGroup').hide();
    }

    crEditCalcTotal();
    bootstrap.Modal.getOrCreateInstance(document.getElementById('editCreditModal')).show();
});

$(document).on('click', '.delete-credit-btn', function () {
    var btn = $(this);
    $('#deleteCreditId').val(btn.data('credit-id'));
    $('#deleteCreditAction').val(btn.data('action'));
    $('#deleteCreditNumber').text(btn.data('credit-number'));
    $('#deleteCustomerName').text(btn.data('customer-name'));
    $('#deleteNotes').val('').prop('required', true);
    bootstrap.Modal.getOrCreateInstance(document.getElementById('deleteCreditModal')).show();
});

var payableCredits = <?php echo json_encode($payableCreditsJson, JSON_UNESCAPED_SLASHES); ?>;
function money(value) {
    return 'MWK ' + (parseFloat(value || 0)).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function escapeHtml(value) {
    return String(value == null ? '' : value).replace(/[&<>'"]/g, function (ch) {
        return {'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[ch];
    });
}
$('#paymentCreditSelect').on('change', function () {
    var credit = payableCredits[$(this).val()];
    if (!credit) {
        $('#paymentDetailPanel').hide();
        $('#paymentCreditId').val('');
        $('#paymentAmount').val('').removeAttr('max');
        return;
    }
    $('#paymentCreditId').val(credit.credit_id);
    $('#pdCustomer').text(credit.customer_name + ' (' + credit.credit_number + ')');
    $('#pdPhone').text(credit.customer_phone || 'No phone recorded');
    $('#pdTotal').text(money(credit.total_amount));
    $('#pdPaid').text(money(credit.amount_paid));
    $('#pdBalance').text(money(credit.balance));
    $('#paymentAmount').attr('max', credit.balance.toFixed(2)).val(credit.balance.toFixed(2));
    $('#pdMaxHint').text('Maximum payment: ' + money(credit.balance));

    var rows = '';
    (credit.items || []).forEach(function (item, idx) {
        rows += '<tr>' +
            '<td>' + (idx + 1) + '</td>' +
            '<td>' + escapeHtml(item.item_name || '-') + '</td>' +
            '<td><code>' + escapeHtml(item.unique_code || '') + '</code></td>' +
            '<td class="text-end">' + money(item.unit_price).replace('MWK ', '') + '</td>' +
            '</tr>';
    });
    if (!rows) {
        rows = '<tr><td colspan="4" class="text-center text-muted">No items found.</td></tr>';
    }
    $('#pdItemsBody').html(rows);
    $('#paymentDetailPanel').show();
});

$('#paymentForm').on('submit', function (e) {
    var credit = payableCredits[$('#paymentCreditId').val()];
    var amount = parseFloat($('#paymentAmount').val()) || 0;
    if (!credit || amount <= 0 || amount - credit.balance > 0.009) {
        e.preventDefault();
        alert('Choose a credit sale and enter an amount not greater than the outstanding balance.');
    }
});
</script>

<?php include '../../includes/footer.php'; ?>
