<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';
require_once __DIR__ . '/../../classes/Laybuy.php';
$database = new Database();
$conn = $database->getConnection();

$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($conn);
$LayBuyPayment = new Laybuy($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$recordId = isset($_GET['record_id']) ? (int)$_GET['record_id'] : 0;
$recordData = $loanLaybuy->getLoanLaybuyById($recordId) ?? [];
$paymentData = $LayBuyPayment->getPaymentDetails($recordId) ?? [];
$codeData = $LayBuyPayment->getCodesDetails($recordId) ?? [];

if (!$recordData || $auth->getUserBranch($_SESSION['user_id']) != ($recordData['branch_id'] ?? null)) {
    header('Location: laybuy_and_loans.php?error=' . urlencode('Lay-buy not found or access denied.'));
    exit();
}

$branchId = (int)($recordData['branch_id'] ?? 0);

$creatorId = $recordData['created_by'] ?? null;
$creatorName = 'Unknown';
if ($creatorId) {
    $creatorName = $auth->getUserName($creatorId);
    if (!$creatorName) {
        error_log("Failed to retrieve username for user_id: $creatorId in record ID: $recordId");
        $creatorName = 'Unknown';
    }
} else {
    error_log("No created_by field found for record ID: $recordId");
}

$recordAmount = round((float)($recordData['amount'] ?? 0), 2);
$totalPaid = round((float)($recordData['total_paid'] ?? 0), 2);
$balance = max(0, $recordAmount - $totalPaid);
$codeValueTotal = 0;
foreach ($codeData as $codeRow) {
    $codeValueTotal += (float)($codeRow['value'] ?? 0);
}
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        @import url('https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap');

        :root { --accent: #7C3AED; --accent-dark: #5B21B6; --ink: #18181B; --sub: #71717A; --line: #E4E4E7; }

        body {
            font-family: 'Manrope', system-ui, -apple-system, sans-serif;
            background: #fff;
            min-height: 100vh;
            color: var(--ink);
            -webkit-font-smoothing: antialiased;
        }

        .top-strip { padding: 22px 24px 0; max-width: 780px; margin: 0 auto; }
        .top-strip a {
            color: var(--sub); text-decoration: none; font-size: .82rem; font-weight: 600;
            display: inline-flex; align-items: center; gap: 6px;
        }
        .top-strip a:hover { color: var(--ink); }
        .top-strip a::before { content: '←'; font-size: .95rem; }

        .wrap { max-width: 780px; margin: 0 auto; padding: 28px 24px 90px; }

        .head { margin-bottom: 34px; }
        .head .eyebrow { font-size: .74rem; font-weight: 700; letter-spacing: .1em; text-transform: uppercase; color: var(--accent); margin-bottom: 8px; }
        .head h1 { font-size: 1.7rem; font-weight: 800; letter-spacing: -.02em; color: var(--ink); }
        .head .sub { font-size: .88rem; color: var(--sub); margin-top: 6px; }

        .stat-row { display: flex; gap: 28px; margin-top: 22px; padding-top: 22px; border-top: 1px solid var(--line); flex-wrap: wrap; }
        .stat .n { font-size: 1.05rem; font-weight: 800; color: var(--ink); }
        .stat .l { font-size: .72rem; color: var(--sub); text-transform: uppercase; letter-spacing: .05em; margin-top: 2px; }
        .stat .n.accent { color: var(--accent); }

        .section { padding: 28px 0; border-bottom: 1px solid var(--line); }
        .section:last-of-type { border-bottom: none; }
        .section-label-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px; flex-wrap: wrap; gap: 10px; }
        .section-label { font-size: .78rem; font-weight: 700; color: var(--ink); }

        .field-row { display: flex; gap: 18px; flex-wrap: wrap; }
        .field { flex: 1; min-width: 180px; margin-bottom: 18px; }
        .field:last-child { margin-bottom: 0; }

        label.lbl { display: block; font-size: .76rem; font-weight: 600; color: var(--sub); margin-bottom: 6px; }
        .ro { font-size: .95rem; color: var(--ink); padding-bottom: 8px; border-bottom: 1.5px solid var(--line); min-height: 1.2em; }

        .table-wrap { width: 100%; overflow-x: auto; }
        .pay-table { width: 100%; border-collapse: collapse; font-size: .86rem; }
        .pay-table th, .pay-table td { padding: 10px 8px; text-align: left; white-space: nowrap; }
        .pay-table th { font-weight: 700; text-transform: uppercase; font-size: .68rem; color: var(--sub); border-bottom: 1.5px solid var(--ink); }
        .pay-table td { border-bottom: 1px solid var(--line); }
        .pay-table tfoot td { font-weight: 800; border-top: 1.5px solid var(--ink); border-bottom: none; }
        .pay-table .empty-row td { text-align: center; color: var(--sub); white-space: normal; }

        .btn-fill {
            background: var(--ink); color: #fff; border: none; padding: 10px 20px; border-radius: 30px;
            font-family: 'Manrope', sans-serif; font-size: .82rem; font-weight: 700; cursor: pointer;
            transition: background .15s; display: inline-flex; align-items: center; gap: 8px; text-decoration: none;
        }
        .btn-fill:hover { background: var(--accent-dark); color: #fff; text-decoration: none; }
        .btn-plain {
            background: transparent; color: var(--sub); border: none; padding: 12px 4px;
            font-family: 'Manrope', sans-serif; font-size: .86rem; font-weight: 600; cursor: pointer; text-decoration: none;
        }
        .btn-plain:hover { color: var(--ink); }
        .btn-del {
            background: transparent; color: #B91C1C; border: none; padding: 0;
            font-family: 'Manrope', sans-serif; font-size: .82rem; font-weight: 600; cursor: pointer; text-decoration: underline;
        }
        .btn-del:hover { color: #7F1D1D; }

        .actions { display: flex; align-items: center; gap: 14px; padding-top: 30px; flex-wrap: wrap; }
    </style>

    <div class="top-strip">
        <a href="laybuy_and_loans.php?branch_id=<?php echo $branchId; ?>">Back to list</a>
    </div>

    <div class="wrap">
        <div class="head">
            <div class="eyebrow">Lay-buy &middot; <?php echo htmlspecialchars(ucfirst($recordData['status'] ?? 'pending')); ?></div>
            <h1>Assign Codes</h1>
            <div class="sub">Ref #<?php echo htmlspecialchars($recordData['record_number'] ?? $recordData['record_id'] ?? 'N/A'); ?> &middot; Prepared by <?php echo htmlspecialchars($creatorName); ?></div>

            <div class="stat-row">
                <div class="stat"><div class="n">MWK <?php echo number_format($recordAmount, 2); ?></div><div class="l">Amount</div></div>
                <div class="stat"><div class="n">MWK <?php echo number_format($totalPaid, 2); ?></div><div class="l">Paid</div></div>
                <div class="stat"><div class="n accent">MWK <?php echo number_format($balance, 2); ?></div><div class="l">Balance</div></div>
            </div>
        </div>

        <div class="section">
            <div class="section-label-row">
                <div class="section-label">Customer</div>
            </div>
            <div class="field-row">
                <div class="field">
                    <label class="lbl">Customer / Company Name</label>
                    <div class="ro"><?php echo htmlspecialchars($recordData['customer_name'] ?? ''); ?></div>
                </div>
                <div class="field">
                    <label class="lbl">Contact Details</label>
                    <div class="ro"><?php echo htmlspecialchars($recordData['customer_contact'] ?? ''); ?></div>
                </div>
                <div class="field">
                    <label class="lbl">Item Name</label>
                    <div class="ro"><?php echo htmlspecialchars($recordData['item_name'] ?? ''); ?></div>
                </div>
            </div>
        </div>

        <div class="section">
            <div class="section-label-row">
                <div class="section-label">Payment History</div>
                <a href="add_payment_form.php?record_id=<?php echo $recordId . '&branch_id=' . $branchId . '&total_paid=' . $totalPaid . '&balance=' . $balance; ?>" class="btn-fill">+ Add Payment</a>
            </div>

            <div class="table-wrap">
                <table class="pay-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Description</th>
                            <th>Amount</th>
                            <th>Recorded By</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($paymentData)): ?>
                            <?php foreach ($paymentData as $payments): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($payments['payment_date'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($payments['notes'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($payments['body_amount'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($payments['username'] ?? ''); ?></td>
                                    <td>
                                        <?php if (isset($payments['id'])): ?>
                                            <button type="button" class="btn-del" onclick="if(confirm('Are you sure you want to delete this payment?')) window.location.href='delete_payment.php?id=<?php echo $payments['id']; ?>';">Delete</button>
                                        <?php else: ?>
                                            <span class="text-danger">ID not found</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr class="empty-row">
                                <td colspan="5">No payment data found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="section">
            <div class="section-label-row">
                <div class="section-label">Code(s) Assigned</div>
                <a href="add_code_form.php?record_id=<?php echo $recordId . '&branch_id=' . $branchId . '&total_paid=' . $totalPaid . '&balance=' . $balance; ?>" class="btn-fill">+ Add Unique Code</a>
            </div>

            <div class="table-wrap">
                <table class="pay-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Unique Code</th>
                            <th>Notes</th>
                            <th>Value</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($codeData)): ?>
                            <?php foreach ($codeData as $codes): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($codes['date_added'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($codes['unique_code'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($codes['notes'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars(number_format((float)($codes['value'] ?? 0), 2)); ?></td>
                                    <td>
                                        <?php if (isset($codes['unique_code'])): ?>
                                            <button type="button" class="btn-del" onclick="if(confirm('Are you sure you want to delete this code?')) window.location.href='delete_codes.php?id=<?php echo urlencode($codes['unique_code']); ?>';">Delete</button>
                                        <?php else: ?>
                                            <span class="text-danger">ID not found</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <tr>
                                <td colspan="3">Total</td>
                                <td><?php echo htmlspecialchars(number_format($codeValueTotal, 2)); ?></td>
                                <td></td>
                            </tr>
                        <?php else: ?>
                            <tr class="empty-row">
                                <td colspan="5">No code assigned.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="actions">
            <a href="laybuy_and_loans.php?branch_id=<?php echo $branchId; ?>" class="btn-plain">Close</a>
        </div>
    </div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
