<?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/Branch.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';

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

$branch = new Branch($conn);
$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($conn);

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

$userRole = $auth->getUserRole($_SESSION['user_id']);
if (!in_array($userRole, ['admin', 'branch', 'warehouse', 'sales'])) {
    header('Location: ../../unauthorized.php');
    exit();
}

$branchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    die("Error: You are not assigned to any branch.");
}

$branchDetails = $branch->getBranchById($branchId);
$cashierName = $auth->getUserName($_SESSION['user_id']);
$recordNumber = 'LB' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_loan_laybuy'])) {
    $itemName = trim($_POST['item_name'] ?? '');
    $customerName = trim($_POST['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? '');
    $amount = (float)($_POST['amount'] ?? 0);
    $status = trim($_POST['status'] ?? 'pending');
    $validityDays = (int)($_POST['validity_days'] ?? 30);
    $notes = trim($_POST['notes'] ?? '');

    if (empty($itemName) || empty($customerName) || empty($customerContact) || $amount <= 0) {
        $errors[] = 'Please fill in all required fields.';
    } else {

        $maxRetries = 3;
        $retryCount = 0;
        do {
            $recordNumber = 'LB' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $result = $loanLaybuy->createLoanLaybuy(
                $branchId,
                $_SESSION['user_id'],
                $recordNumber,
                $itemName,
                $customerName,
                $customerContact,
                $amount,
                $status,
                $validityDays,
                $notes
            );
            $retryCount++;
        } while (!$result['success'] && strpos($result['message'], 'Duplicate entry') !== false && $retryCount < $maxRetries);

        if ($result['success']) {
            $queryParams = http_build_query([
                'success' => 'Lay-buy created successfully.',
                'branch_id' => $branchId
            ]);
            header('Location: laybuy_and_loans.php?' . $queryParams);
            exit();
        } else {
            $errors[] = 'Failed to create record: ' . $result['message'];
        }
    }
}
?>
<?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; }

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

        .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; }

        .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 .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 $branchId; ?>">Back to list</a>
    </div>

    <div class="wrap">
        <div class="head">
            <div class="eyebrow">New Record &middot; No. <?php echo htmlspecialchars($recordNumber); ?></div>
            <h1>Create Lay-Buy</h1>
            <div class="sub"><?php echo htmlspecialchars($companyName); ?> &middot; Prepared by <?php echo htmlspecialchars($cashierName); ?></div>
        </div>

        <?php if (!empty($errors)): ?>
        <div class="alert">
            <?php foreach ($errors as $error): ?>
                <span>&#9888; <?php echo htmlspecialchars($error); ?></span>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <form method="post" action="" id="loanLaybuyForm" 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"
                           placeholder="Customer/Company 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></textarea>
                </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"
                           placeholder="Enter 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"
                               placeholder="0.00" step="0.01" min="0.01" required>
                    </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">Pending</option>
                            <option value="approved">Approved</option>
                            <option value="completed">Completed</option>
                        </select>
                    </div>
                    <div class="field">
                        <label class="lbl" for="validity_days">Valid for (days) <span class="req">*</span></label>
                        <input type="number" class="in" id="validity_days" name="validity_days"
                               value="30" min="1" max="365" required>
                    </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..."></textarea>
                </div>
            </div>

            <input type="hidden" name="create_loan_laybuy" value="1">

            <div class="actions">
                <button type="submit" class="btn-fill">Create Lay-Buy</button>
                <button type="button" class="btn-line" onclick="previewRecord()">Preview</button>
                <a href="laybuy_and_loans.php?branch_id=<?php echo $branchId; ?>" 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($recordNumber); ?></span></p>
                            <p><strong>Date</strong> <span><?php echo date('d M Y'); ?></span></p>
                            <p><strong>Prepared By</strong> <span><?php echo htmlspecialchars($cashierName); ?></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>
                            <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">No additional notes provided.</p>
                    </div>
                    <div class="receipt-validity">
                        <p>This record is valid until <span id="preview-valid-until-footer"></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 itemName = document.getElementById('item_name').value || 'Not provided';
            const customerName = document.getElementById('customer_name').value || 'Not provided';
            const customerContact = document.getElementById('customer_contact').value || 'Not provided';
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const status = document.getElementById('status').value || 'pending';
            const validityDays = parseInt(document.getElementById('validity_days').value) || 30;
            const notes = document.getElementById('notes').value || 'No additional notes provided.';

            if (!itemName || !customerName || !customerContact || amount <= 0) {
                alert('Please fill in all required fields.');
                return;
            }

            const validUntil = new Date();
            validUntil.setDate(validUntil.getDate() + validityDays);
            const formattedValidUntil = validUntil.toISOString().split('T')[0];

            document.getElementById('preview-customer-name').textContent = customerName;
            document.getElementById('preview-customer-contact').textContent = customerContact;
            document.getElementById('preview-valid-until').textContent = formattedValidUntil;
            document.getElementById('preview-valid-until-footer').textContent = formattedValidUntil;
            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)}`;
            document.getElementById('preview-status').textContent = status.charAt(0).toUpperCase() + status.slice(1);
            document.getElementById('preview-notes').textContent = notes;

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

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('loanLaybuyForm');
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
