<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
$companyDetails = [
    'address' => 'P.O. Box 109, Limbe, Malawi, South East Africa',
    'phone' => '+265 (0) 212 273 707 / +265 (0) 888 737 654',
];
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';

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

$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($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) ?? [];
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();
}

$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");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customerName = trim($_POST['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? '');
    $validUntilRaw = trim($_POST['valid_until'] ?? '');
    $status = trim($_POST['status'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $itemName = trim($_POST['item_name'] ?? '');
    $amount = is_numeric($_POST['amount'] ?? null) ? (float)$_POST['amount'] : -1;

    $errors = [];
    if ($customerName === '') {
        $errors[] = 'Customer/company name is required.';
    }
    if ($customerContact === '') {
        $errors[] = 'Contact details are required.';
    }
    if (!DateTime::createFromFormat('Y-m-d', $validUntilRaw)) {
        $errors[] = 'A valid "Valid Until" date is required.';
    }
    if ($itemName === '') {
        $errors[] = 'Item name is required.';
    }
    if (!in_array($status, ['pending', 'approved', 'completed'], true)) {
        $errors[] = 'Invalid status selected.';
    }
    if ($amount < 0) {
        $errors[] = 'Amount must be a valid, non-negative number.';
    }
    $existingPaid = round((float)($recordData['total_paid'] ?? 0), 2);
    if ($amount >= 0 && $amount < $existingPaid) {
        $errors[] = 'Amount cannot be less than the MWK ' . number_format($existingPaid, 2) . ' already paid on this record.';
    }

    if (empty($errors)) {
        $result = $loanLaybuy->updateLoanLaybuy($recordId, $customerName, $customerContact, $validUntilRaw, $status, $itemName, $amount, $notes);
        if ($result) {
            header('Location: laybuy_and_loans.php?success=' . urlencode('Record updated successfully.') . '&branch_id=' . $recordData['branch_id']);
            exit();
        }
        $errors[] = 'Failed to update record.';
    }

    header('Location: edit_loan_or_laybuy.php?record_id=' . $recordId . '&error=' . urlencode(implode(' ', $errors)));
    exit();
}

$existingPaid = round((float)($recordData['total_paid'] ?? 0), 2);
$recordAmount = round((float)($recordData['amount'] ?? 0), 2);
$recordBalance = max(0, $recordAmount - $existingPaid);
?>
<?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: 640px; 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: 640px; 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 { }
        .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); }

        .alert {
            padding: 12px 0; margin-bottom: 26px; font-size: .86rem; color: #B91C1C;
            border-bottom: 1px solid var(--line); display: flex; gap: 8px;
        }

        .section { padding: 28px 0; border-bottom: 1px solid var(--line); }
        .section:last-of-type { border-bottom: none; }
        .section-label { font-size: .78rem; font-weight: 700; color: var(--ink); margin-bottom: 18px; }

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

        label.lbl { display: block; font-size: .76rem; font-weight: 600; color: var(--sub); margin-bottom: 6px; }
        .req { color: var(--accent); }

        .in {
            width: 100%; border: none; border-bottom: 1.5px solid var(--line);
            padding: 8px 2px; font-size: .95rem; font-family: 'Manrope', sans-serif; color: var(--ink);
            background: transparent; border-radius: 0; transition: border-color .15s;
        }
        .in:focus { outline: none; border-bottom-color: var(--accent); }
        textarea.in { resize: vertical; min-height: 60px; }
        select.in { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%2371717A'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 4px center; padding-right: 18px; }
        .hint { font-size: .74rem; color: var(--sub); margin-top: 6px; }

        .actions { display: flex; align-items: center; gap: 14px; padding-top: 30px; flex-wrap: wrap; }
        .btn-fill {
            background: var(--ink); color: #fff; border: none; padding: 12px 26px; border-radius: 30px;
            font-family: 'Manrope', sans-serif; font-size: .86rem; 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-line {
            background: transparent; color: var(--ink); border: none; padding: 12px 4px;
            font-family: 'Manrope', sans-serif; font-size: .86rem; font-weight: 600; cursor: pointer; text-decoration: underline;
        }
        .btn-line:hover { color: var(--accent); }
        .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); }

        @media (max-width: 480px) {
            .actions { flex-direction: column-reverse; align-items: stretch; }
            .btn-fill { justify-content: center; }
        }

        /* ── Preview modal ────────────────────────────── */
        .preview-modal { max-width: 640px; margin: 40px auto; }
        #previewModal .modal-content { border: none; border-radius: 0; font-family: 'Manrope', sans-serif; }
        #previewModal .modal-header { border: none; padding: 30px 30px 0; }
        #previewModal .close { font-size: 1.6rem; font-weight: 300; opacity: .4; }
        #previewModal .close:hover { opacity: 1; }
        #previewModal .modal-footer { border: none; padding: 20px 30px 30px; }
        .preview-content { padding: 10px 30px 20px; }
        .preview-content .logo-row { display: flex; align-items: center; gap: 12px; margin-bottom: 22px; }
        .preview-content .logo-row img { height: 36px; width: auto; }
        .preview-content .logo-row .cn { font-weight: 800; font-size: 1rem; }
        .preview-content .logo-row .doc { margin-left: auto; font-size: .68rem; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: var(--accent); }
        .preview-info-grid { display: flex; gap: 20px; flex-wrap: wrap; margin-bottom: 20px; padding-bottom: 18px; border-bottom: 1px solid var(--line); }
        .preview-info-col { flex: 1; min-width: 190px; }
        .preview-info-col p { display: flex; justify-content: space-between; gap: 8px; font-size: .84rem; margin: 0 0 9px; }
        .preview-info-col p strong { color: var(--sub); font-weight: 600; }
        .preview-status-badge { font-weight: 700; text-transform: capitalize; color: var(--accent); font-size: .84rem; }
        .preview-table { width: 100%; margin-bottom: 18px; border-collapse: collapse; font-size: .86rem; }
        .preview-table th, .preview-table td { padding: 9px 4px; }
        .preview-table th { font-weight: 700; text-transform: uppercase; font-size: .68rem; color: var(--sub); border-bottom: 1.5px solid var(--ink); }
        .preview-table td { border-bottom: 1px solid var(--line); }
        .preview-table tfoot td { font-weight: 800; font-size: .98rem; border-top: 1.5px solid var(--ink); border-bottom: none; }
        .receipt-notes h5 { font-size: .74rem; text-transform: uppercase; letter-spacing: .04em; color: var(--sub); margin-bottom: 5px; }
        .receipt-notes p { font-size: .87rem; }
        .receipt-validity { font-size: .78rem; font-style: italic; color: var(--sub); margin-top: 14px; }
    </style>

    <div class="top-strip">
        <a href="laybuy_and_loans.php?branch_id=<?php echo (int)($recordData['branch_id'] ?? 0); ?>">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>Edit Record</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($existingPaid, 2); ?></div><div class="l">Paid</div></div>
                <div class="stat"><div class="n accent">MWK <?php echo number_format($recordBalance, 2); ?></div><div class="l">Balance</div></div>
            </div>
        </div>

        <?php if (isset($_GET['error'])) { ?>
            <div class="alert"><span>&#9888;</span><span><?php echo htmlspecialchars($_GET['error']); ?></span></div>
        <?php } ?>

        <form method="POST" action="" id="recordForm" class="needs-validation" novalidate>
            <div class="section">
                <div class="section-label">Customer</div>
                <div class="field">
                    <label class="lbl" for="customer_name">Customer / Company Name <span class="req">*</span></label>
                    <input type="text" class="in" id="customer_name" name="customer_name"
                           value="<?php echo htmlspecialchars($recordData['customer_name'] ?? ''); ?>" required>
                </div>
                <div class="field">
                    <label class="lbl" for="customer_contact">Contact Details <span class="req">*</span></label>
                    <textarea class="in" id="customer_contact" name="customer_contact"
                              placeholder="Address, Phone, Email" required><?php echo htmlspecialchars($recordData['customer_contact'] ?? ''); ?></textarea>
                </div>
                <div class="field">
                    <label class="lbl" for="valid_until">Valid Until <span class="req">*</span></label>
                    <input type="date" class="in" id="valid_until" name="valid_until"
                           value="<?php echo htmlspecialchars($recordData['valid_until'] ?? ''); ?>" required>
                </div>
            </div>

            <div class="section">
                <div class="section-label">Record</div>
                <div class="field">
                    <label class="lbl" for="item_name">Item Name <span class="req">*</span></label>
                    <input type="text" class="in" id="item_name" name="item_name"
                           value="<?php echo htmlspecialchars($recordData['item_name'] ?? ''); ?>" required>
                </div>
                <div class="field-row">
                    <div class="field">
                        <label class="lbl" for="amount">Amount (MWK) <span class="req">*</span></label>
                        <input type="number" class="in" id="amount" name="amount"
                               value="<?php echo htmlspecialchars($recordData['amount'] ?? 0); ?>" step="0.01" min="<?php echo htmlspecialchars($recordData['total_paid'] ?? 0); ?>" required>
                        <?php if ($existingPaid > 0): ?>
                        <div class="hint">Can't go below MWK <?php echo number_format($existingPaid, 2); ?> already paid.</div>
                        <?php endif; ?>
                    </div>
                    <div class="field">
                        <label class="lbl" for="status">Status <span class="req">*</span></label>
                        <select class="in" id="status" name="status" required>
                            <option value="pending" <?php echo ($recordData['status'] ?? 'pending') === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="approved" <?php echo ($recordData['status'] ?? 'pending') === 'approved' ? 'selected' : ''; ?>>Approved</option>
                            <option value="completed" <?php echo ($recordData['status'] ?? 'pending') === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="section">
                <div class="section-label">Notes</div>
                <div class="field">
                    <textarea class="in" id="notes" name="notes" rows="3"
                              placeholder="Any additional notes or terms..."><?php echo htmlspecialchars($recordData['notes'] ?? ''); ?></textarea>
                </div>
            </div>

            <div class="actions">
                <button type="submit" class="btn-fill">Update Record</button>
                <button type="button" class="btn-line" onclick="previewRecord()">Preview</button>
                <a href="laybuy_and_loans.php?branch_id=<?php echo (int)($recordData['branch_id'] ?? 0); ?>" class="btn-plain">Cancel</a>
            </div>
        </form>
    </div>

    <div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl preview-modal" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="previewModalLabel" style="display:none;">Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="preview-content">
                    <div class="logo-row">
                        <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo">
                        <span class="cn"><?php echo htmlspecialchars($companyName); ?></span>
                        <span class="doc">LAY-BUY</span>
                    </div>
                    <div class="preview-info-grid">
                        <div class="preview-info-col">
                            <p><strong>Record #</strong> <span><?php echo htmlspecialchars($recordData['record_number'] ?? $recordData['record_id'] ?? 'N/A'); ?></span></p>
                            <p><strong>Date</strong> <span><?php echo (new DateTime($recordData['created_at'] ?? 'now'))->format('d M Y'); ?></span></p>
                            <p><strong>Prepared By</strong> <span><?php echo htmlspecialchars($creatorName); ?></span></p>
                        </div>
                        <div class="preview-info-col">
                            <p><strong>Customer</strong> <span id="preview-customer-name"></span></p>
                            <p><strong>Contact</strong> <span id="preview-customer-contact"></span></p>
                            <p><strong>Valid Until</strong> <span id="preview-valid-until"></span></p>
                            <p><strong>Status</strong> <span id="preview-status" class="preview-status-badge"></span></p>
                        </div>
                    </div>
                    <table class="preview-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Item Name</th>
                                <th class="text-end">Amount (MWK)</th>
                            </tr>
                        </thead>
                        <tbody id="preview-items">
                            <tr>
                                <td>1</td>
                                <td id="preview-item-name"></td>
                                <td id="preview-amount" class="text-end"></td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="2" class="text-end">Total</td>
                                <td id="preview-total" class="text-end"></td>
                            </tr>
                        </tfoot>
                    </table>
                    <div class="receipt-notes">
                        <h5>Notes</h5>
                        <p id="preview-notes"><?php echo htmlspecialchars($recordData['notes'] ?? 'No additional notes provided.'); ?></p>
                    </div>
                    <div class="receipt-validity">
                        <p>This record is valid until <span id="preview-valid-until-footer"><?php echo htmlspecialchars($recordData['valid_until'] ?? 'N/A'); ?></span>.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-plain" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function previewRecord() {
            const customerName = document.getElementById('customer_name').value || '<?php echo htmlspecialchars($recordData['customer_name'] ?? 'Not provided'); ?>';
            const customerContact = document.getElementById('customer_contact').value || '<?php echo htmlspecialchars($recordData['customer_contact'] ?? 'Not provided'); ?>';
            const validUntil = document.getElementById('valid_until').value || '<?php echo htmlspecialchars($recordData['valid_until'] ?? ''); ?>';
            const notes = document.getElementById('notes').value || '<?php echo htmlspecialchars($recordData['notes'] ?? 'No additional notes provided.'); ?>';
            const itemName = document.getElementById('item_name').value || '<?php echo htmlspecialchars($recordData['item_name'] ?? 'Not provided'); ?>';
            const amount = parseFloat(document.getElementById('amount').value) || <?php echo (float)($recordData['amount'] ?? 0); ?>;
            const status = document.getElementById('status').value || '<?php echo htmlspecialchars($recordData['status'] ?? 'pending'); ?>';

            document.getElementById('preview-customer-name').textContent = customerName;
            document.getElementById('preview-customer-contact').textContent = customerContact;
            document.getElementById('preview-valid-until').textContent = validUntil;
            document.getElementById('preview-valid-until-footer').textContent = validUntil;
            document.getElementById('preview-notes').textContent = notes;
            document.getElementById('preview-item-name').textContent = itemName;
            document.getElementById('preview-amount').textContent = `MWK ${amount.toFixed(2)}`;
            document.getElementById('preview-total').textContent = `MWK ${amount.toFixed(2)}`;
            const statusEl = document.getElementById('preview-status');
            statusEl.textContent = status.charAt(0).toUpperCase() + status.slice(1);

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

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('recordForm');
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                const amountInput = document.getElementById('amount');
                const minAmount = parseFloat(amountInput.min) || 0;
                const amount = parseFloat(amountInput.value) || 0;
                if (amount < minAmount) {
                    amountInput.value = minAmount;
                }
                form.classList.add('was-validated');
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
