<?php
/**
 * Create Sale
 * LandSales Pro - Record a new plot sale
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$errors = [];

// Pre-selected values
$selectedPlotId = $_GET['plot_id'] ?? $_POST['plot_id'] ?? null;
$selectedBuyerId = $_GET['buyer_id'] ?? $_POST['buyer_id'] ?? null;

// Get agents
$agents = db_fetch_all("SELECT * FROM agents WHERE user_id = ? AND status = 'active' ORDER BY full_name", 'i', [$userId]);

// Get pre-selected plot details
$selectedPlot = null;
if ($selectedPlotId) {
    $selectedPlot = db_fetch_one("SELECT p.*, pr.name as project_name
        FROM plots p JOIN projects pr ON p.project_id = pr.id
        WHERE p.id = ? AND p.user_id = ? AND p.status = 'available'", 'ii', [$selectedPlotId, $userId]);
}

// Get pre-selected buyer details
$selectedBuyer = null;
if ($selectedBuyerId) {
    $selectedBuyer = db_fetch_one("SELECT * FROM buyers WHERE id = ? AND user_id = ?", 'ii', [$selectedBuyerId, $userId]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $plotId = intval($_POST['plot_id'] ?? 0);
    $buyerId = intval($_POST['buyer_id'] ?? 0);
    $agentId = intval($_POST['agent_id'] ?? 0) ?: null;
    $saleDate = $_POST['sale_date'] ?? date('Y-m-d');
    $totalPrice = floatval($_POST['total_price'] ?? 0);
    $depositAmount = floatval($_POST['deposit_amount'] ?? 0);
    $paymentType = $_POST['payment_type'] ?? 'cash';
    $installmentMonths = intval($_POST['installment_months'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');

    // Validation
    if (!$plotId) $errors[] = "Please select a plot";
    if (!$buyerId) $errors[] = "Please select a buyer";
    if ($totalPrice <= 0) $errors[] = "Please enter a valid total price";
    if ($depositAmount < 0) $errors[] = "Deposit cannot be negative";
    if ($depositAmount > $totalPrice) $errors[] = "Deposit cannot exceed total price";
    if ($paymentType === 'installment' && $installmentMonths < 1) {
        $errors[] = "Please enter the number of installment months";
    }

    // Verify plot is available
    if ($plotId && empty($errors)) {
        $plot = db_fetch_one("SELECT * FROM plots WHERE id = ? AND user_id = ? AND status = 'available'", 'ii', [$plotId, $userId]);
        if (!$plot) {
            $errors[] = "Selected plot is not available";
        }
    }

    // Verify buyer exists
    if ($buyerId && empty($errors)) {
        $buyer = db_fetch_one("SELECT * FROM buyers WHERE id = ? AND user_id = ?", 'ii', [$buyerId, $userId]);
        if (!$buyer) {
            $errors[] = "Invalid buyer selected";
        }
    }

    if (empty($errors)) {
        db_begin();
        try {
            // Generate sale number
            $year = date('Y');
            $lastSale = db_fetch_one("SELECT sale_number FROM sales WHERE user_id = ? AND sale_number LIKE ? ORDER BY id DESC LIMIT 1",
                'is', [$userId, "SL{$year}%"]);
            if ($lastSale) {
                $lastNum = intval(substr($lastSale['sale_number'], -4));
                $saleNumber = "SL{$year}" . str_pad($lastNum + 1, 4, '0', STR_PAD_LEFT);
            } else {
                $saleNumber = "SL{$year}0001";
            }

            // Insert sale
            $sql = "INSERT INTO sales (user_id, sale_number, plot_id, buyer_id, agent_id, sale_date, total_price,
                    deposit_amount, payment_type, installment_months, notes, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')";

            db_execute($sql, 'isiiisddsis', [
                $userId, $saleNumber, $plotId, $buyerId, $agentId, $saleDate,
                $totalPrice, $depositAmount, $paymentType, $installmentMonths, $notes
            ]);

            $saleId = db_last_id();

            // Update plot status
            db_execute("UPDATE plots SET status = 'sold' WHERE id = ?", 'i', [$plotId]);

            // If deposit paid, record payment
            if ($depositAmount > 0) {
                $paymentNumber = "PY{$year}" . str_pad(1, 4, '0', STR_PAD_LEFT);
                $paymentSql = "INSERT INTO payments (user_id, sale_id, payment_number, amount, payment_date, payment_method, notes, status)
                              VALUES (?, ?, ?, ?, ?, 'cash', 'Initial deposit', 'confirmed')";
                db_execute($paymentSql, 'iisds', [$userId, $saleId, $paymentNumber, $depositAmount, $saleDate]);
            }

            // Create payment schedule for installments
            if ($paymentType === 'installment' && $installmentMonths > 0) {
                $balance = $totalPrice - $depositAmount;
                $monthlyAmount = $balance / $installmentMonths;

                for ($i = 1; $i <= $installmentMonths; $i++) {
                    $dueDate = date('Y-m-d', strtotime("+{$i} months", strtotime($saleDate)));
                    $scheduleSql = "INSERT INTO payment_schedule (sale_id, installment_number, amount, due_date, status)
                                   VALUES (?, ?, ?, ?, 'pending')";
                    db_execute($scheduleSql, 'iids', [$saleId, $i, $monthlyAmount, $dueDate]);
                }
            }

            db_commit();
            logActivity('sale_created', "Recorded sale {$saleNumber} for plot ID {$plotId}");
            setFlashMessage('success', "Sale {$saleNumber} recorded successfully!");
            header('Location: view.php?id=' . $saleId);
            exit;

        } catch (Exception $e) {
            db_rollback();
            $errors[] = "Failed to record sale: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Record Sale - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Record Sale</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST" class="card" id="saleForm">
                    <div class="card-header">
                        <h3><i class="fas fa-handshake"></i> Sale Details</h3>
                    </div>
                    <div class="card-body">
                        <!-- Plot Search -->
                        <div class="form-group">
                            <label>Search Plot *</label>
                            <div class="autocomplete-wrapper">
                                <input type="hidden" name="plot_id" id="plot_id" value="<?php echo $selectedPlotId ?? ''; ?>" required>
                                <div class="search-box" id="plotSearchBox">
                                    <i class="fas fa-search"></i>
                                    <input type="text" id="plotSearch" class="form-control"
                                           placeholder="Type plot number or project name to search..."
                                           value="<?php echo $selectedPlot ? "Plot {$selectedPlot['plot_number']} - {$selectedPlot['project_name']}" : ''; ?>"
                                           autocomplete="off">
                                    <?php if ($selectedPlot): ?>
                                    <button type="button" class="clear-btn" onclick="clearPlot()"><i class="fas fa-times"></i></button>
                                    <?php endif; ?>
                                </div>
                                <div class="autocomplete-results" id="plotResults"></div>
                            </div>
                            <small class="form-text">Search by plot number, project name, or block</small>
                        </div>

                        <!-- Selected Plot Preview -->
                        <div class="plot-preview" id="plotPreview" style="<?php echo $selectedPlot ? '' : 'display:none'; ?>">
                            <div class="preview-item">
                                <span class="preview-label">Plot</span>
                                <span class="preview-value" id="previewPlotNumber"><?php echo $selectedPlot['plot_number'] ?? ''; ?></span>
                            </div>
                            <div class="preview-item">
                                <span class="preview-label">Project</span>
                                <span class="preview-value" id="previewProject"><?php echo htmlspecialchars($selectedPlot['project_name'] ?? ''); ?></span>
                            </div>
                            <div class="preview-item">
                                <span class="preview-label">Size</span>
                                <span class="preview-value" id="previewSize"><?php echo $selectedPlot ? number_format($selectedPlot['size']) . ' ' . $selectedPlot['size_unit'] : ''; ?></span>
                            </div>
                            <div class="preview-item">
                                <span class="preview-label">Price</span>
                                <span class="preview-value text-success" id="previewPrice"><?php echo $selectedPlot ? 'TZS ' . number_format($selectedPlot['price']) : ''; ?></span>
                            </div>
                        </div>

                        <!-- Buyer Search -->
                        <div class="form-group">
                            <label>Search Buyer *</label>
                            <div class="input-with-action">
                                <div class="autocomplete-wrapper" style="flex:1;">
                                    <input type="hidden" name="buyer_id" id="buyer_id" value="<?php echo $selectedBuyerId ?? ''; ?>" required>
                                    <div class="search-box" id="buyerSearchBox">
                                        <i class="fas fa-search"></i>
                                        <input type="text" id="buyerSearch" class="form-control"
                                               placeholder="Type buyer name, phone, or ID to search..."
                                               value="<?php echo $selectedBuyer ? "{$selectedBuyer['full_name']} ({$selectedBuyer['phone']})" : ''; ?>"
                                               autocomplete="off">
                                        <?php if ($selectedBuyer): ?>
                                        <button type="button" class="clear-btn" onclick="clearBuyer()"><i class="fas fa-times"></i></button>
                                        <?php endif; ?>
                                    </div>
                                    <div class="autocomplete-results" id="buyerResults"></div>
                                </div>
                                <a href="../buyers/create.php?redirect=sale" class="btn btn-outline btn-sm">
                                    <i class="fas fa-plus"></i> New
                                </a>
                            </div>
                            <small class="form-text">Search by name, phone number, email, or ID number</small>
                        </div>

                        <!-- Selected Buyer Preview -->
                        <div class="buyer-preview" id="buyerPreview" style="<?php echo $selectedBuyer ? '' : 'display:none'; ?>">
                            <div class="buyer-info">
                                <i class="fas fa-user-circle"></i>
                                <div>
                                    <strong id="previewBuyerName"><?php echo htmlspecialchars($selectedBuyer['full_name'] ?? ''); ?></strong>
                                    <span id="previewBuyerPhone"><?php echo $selectedBuyer['phone'] ?? ''; ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- Agent (Optional) -->
                        <?php if (!empty($agents)): ?>
                        <div class="form-group">
                            <label for="agent_id">Sales Agent (Optional)</label>
                            <select name="agent_id" id="agent_id" class="form-control">
                                <option value="">-- No Agent --</option>
                                <?php foreach ($agents as $agent): ?>
                                <option value="<?php echo $agent['id']; ?>" <?php echo ($_POST['agent_id'] ?? '') == $agent['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($agent['full_name']); ?> (<?php echo $agent['commission_rate']; ?>% commission)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="sale_date">Sale Date *</label>
                                <input type="date" name="sale_date" id="sale_date" class="form-control"
                                       value="<?php echo $_POST['sale_date'] ?? date('Y-m-d'); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="total_price">Total Price (TZS) *</label>
                                <input type="number" name="total_price" id="total_price" class="form-control"
                                       value="<?php echo $_POST['total_price'] ?? ($selectedPlot['price'] ?? ''); ?>"
                                       min="0" required onchange="calculateBalance()">
                            </div>
                        </div>

                        <!-- Payment Type -->
                        <div class="form-group">
                            <label>Payment Type *</label>
                            <div class="radio-group">
                                <label class="radio-option">
                                    <input type="radio" name="payment_type" value="cash"
                                           <?php echo ($_POST['payment_type'] ?? 'cash') === 'cash' ? 'checked' : ''; ?>
                                           onchange="toggleInstallments()">
                                    <span class="radio-label">
                                        <i class="fas fa-money-bill-wave"></i> Full Cash Payment
                                    </span>
                                </label>
                                <label class="radio-option">
                                    <input type="radio" name="payment_type" value="installment"
                                           <?php echo ($_POST['payment_type'] ?? '') === 'installment' ? 'checked' : ''; ?>
                                           onchange="toggleInstallments()">
                                    <span class="radio-label">
                                        <i class="fas fa-calendar-alt"></i> Installment Plan
                                    </span>
                                </label>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="deposit_amount">Deposit/Down Payment (TZS)</label>
                                <input type="number" name="deposit_amount" id="deposit_amount" class="form-control"
                                       value="<?php echo $_POST['deposit_amount'] ?? ''; ?>"
                                       placeholder="0" min="0" onchange="calculateBalance()">
                            </div>
                            <div class="form-group installment-field" style="display: none;">
                                <label for="installment_months">Number of Months</label>
                                <input type="number" name="installment_months" id="installment_months" class="form-control"
                                       value="<?php echo $_POST['installment_months'] ?? '12'; ?>"
                                       placeholder="12" min="1" max="60" onchange="calculateBalance()">
                            </div>
                        </div>

                        <!-- Payment Summary -->
                        <div class="payment-summary" id="paymentSummary" style="display: none;">
                            <h4><i class="fas fa-calculator"></i> Payment Summary</h4>
                            <div class="summary-row">
                                <span>Total Price:</span>
                                <span id="summaryTotal">TZS 0</span>
                            </div>
                            <div class="summary-row">
                                <span>Deposit:</span>
                                <span id="summaryDeposit">TZS 0</span>
                            </div>
                            <div class="summary-row">
                                <span>Balance:</span>
                                <span id="summaryBalance" class="text-warning">TZS 0</span>
                            </div>
                            <div class="summary-row installment-info" style="display: none;">
                                <span>Monthly Payment:</span>
                                <span id="summaryMonthly" class="text-primary">TZS 0</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="notes">Notes</label>
                            <textarea name="notes" id="notes" class="form-control" rows="2"
                                      placeholder="Additional notes about this sale..."><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="index.php" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Record Sale
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-sm { padding: 0.5rem 0.75rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .form-container { max-width: 700px; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; gap: 0.75rem; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.5rem; }
        .card-footer { padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 1rem; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; transition: all 0.2s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        textarea.form-control { resize: vertical; min-height: 70px; }
        .form-text { font-size: 0.75rem; color: #94a3b8; margin-top: 0.25rem; }

        .input-with-action { display: flex; gap: 0.5rem; align-items: flex-start; }

        /* Autocomplete Styles */
        .autocomplete-wrapper { position: relative; }
        .search-box { position: relative; display: flex; align-items: center; }
        .search-box i.fa-search { position: absolute; left: 1rem; color: #94a3b8; z-index: 1; }
        .search-box input { padding-left: 2.5rem; padding-right: 2.5rem; }
        .search-box .clear-btn { position: absolute; right: 0.5rem; background: #f1f5f9; border: none; width: 24px; height: 24px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: #64748b; }
        .search-box .clear-btn:hover { background: #e2e8f0; color: #dc2626; }

        .autocomplete-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            max-height: 300px;
            overflow-y: auto;
            z-index: 100;
            display: none;
        }
        .autocomplete-results.show { display: block; }
        .autocomplete-item {
            padding: 0.75rem 1rem;
            cursor: pointer;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.15s;
        }
        .autocomplete-item:hover { background: #f8fafc; }
        .autocomplete-item:last-child { border-bottom: none; }
        .autocomplete-item .item-main { font-weight: 500; color: #1e293b; }
        .autocomplete-item .item-sub { font-size: 0.8rem; color: #64748b; margin-top: 0.25rem; }
        .autocomplete-item .item-price { color: #16a34a; font-weight: 600; }
        .autocomplete-empty { padding: 1rem; text-align: center; color: #94a3b8; font-size: 0.875rem; }

        .plot-preview {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 1px solid #86efac;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1.25rem;
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
        }
        .preview-item { text-align: center; }
        .preview-label { font-size: 0.75rem; color: #16a34a; display: block; margin-bottom: 0.25rem; }
        .preview-value { font-weight: 600; color: #166534; }
        .preview-value.text-success { color: #16a34a; }

        .buyer-preview {
            background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            border: 1px solid #93c5fd;
            border-radius: 10px;
            padding: 0.75rem 1rem;
            margin-bottom: 1.25rem;
        }
        .buyer-info { display: flex; align-items: center; gap: 0.75rem; }
        .buyer-info i { font-size: 2rem; color: #3b82f6; }
        .buyer-info strong { display: block; color: #1e40af; }
        .buyer-info span { font-size: 0.85rem; color: #3b82f6; }

        .radio-group { display: flex; gap: 1rem; }
        .radio-option { flex: 1; }
        .radio-option input { display: none; }
        .radio-label {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
            color: #64748b;
        }
        .radio-option input:checked + .radio-label {
            border-color: #667eea;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
            color: #667eea;
        }

        .payment-summary {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 1rem 1.25rem;
            margin-bottom: 1.25rem;
        }
        .payment-summary h4 {
            margin: 0 0 0.75rem 0;
            font-size: 0.9rem;
            color: #64748b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e2e8f0;
            font-size: 0.9rem;
        }
        .summary-row:last-child { border-bottom: none; }
        .summary-row span:last-child { font-weight: 600; }
        .text-warning { color: #d97706; }
        .text-primary { color: #667eea; }
        .text-success { color: #16a34a; }

        @media (max-width: 768px) {
            .form-row { grid-template-columns: 1fr; }
            .radio-group { flex-direction: column; }
            .plot-preview { grid-template-columns: repeat(2, 1fr); }
        }

        @media (max-width: 576px) {
            .card-footer { flex-direction: column-reverse; }
            .card-footer .btn { width: 100%; justify-content: center; }
            .input-with-action { flex-direction: column; }
        }
    </style>

    <script>
        const SITE_URL = '<?php echo SITE_URL; ?>';
        let searchTimeout;

        // Plot Search
        const plotSearch = document.getElementById('plotSearch');
        const plotResults = document.getElementById('plotResults');
        const plotIdInput = document.getElementById('plot_id');

        plotSearch.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const query = this.value.trim();

            if (query.length < 1) {
                plotResults.classList.remove('show');
                return;
            }

            searchTimeout = setTimeout(() => {
                fetch(`${SITE_URL}/ajax/search-plots.php?q=${encodeURIComponent(query)}&status=available`)
                    .then(r => r.json())
                    .then(data => {
                        if (data.success && data.results.length > 0) {
                            plotResults.innerHTML = data.results.map(plot => `
                                <div class="autocomplete-item" onclick="selectPlot(${plot.id}, '${escapeHtml(plot.plot_number)}', '${escapeHtml(plot.project_name)}', '${plot.size}', ${plot.price}, '${plot.price_formatted}')">
                                    <div class="item-main">Plot ${escapeHtml(plot.plot_number)} - ${escapeHtml(plot.project_name)}</div>
                                    <div class="item-sub">${plot.size} | <span class="item-price">${plot.price_formatted}</span></div>
                                </div>
                            `).join('');
                        } else {
                            plotResults.innerHTML = '<div class="autocomplete-empty">No available plots found</div>';
                        }
                        plotResults.classList.add('show');
                    });
            }, 300);
        });

        plotSearch.addEventListener('focus', function() {
            if (this.value.trim().length >= 1) {
                this.dispatchEvent(new Event('input'));
            }
        });

        function selectPlot(id, plotNumber, projectName, size, price, priceFormatted) {
            plotIdInput.value = id;
            plotSearch.value = `Plot ${plotNumber} - ${projectName}`;
            plotResults.classList.remove('show');

            // Update preview
            document.getElementById('previewPlotNumber').textContent = plotNumber;
            document.getElementById('previewProject').textContent = projectName;
            document.getElementById('previewSize').textContent = size;
            document.getElementById('previewPrice').textContent = priceFormatted;
            document.getElementById('plotPreview').style.display = 'grid';

            // Update price
            document.getElementById('total_price').value = price;
            calculateBalance();

            // Add clear button
            let clearBtn = document.querySelector('#plotSearchBox .clear-btn');
            if (!clearBtn) {
                clearBtn = document.createElement('button');
                clearBtn.type = 'button';
                clearBtn.className = 'clear-btn';
                clearBtn.innerHTML = '<i class="fas fa-times"></i>';
                clearBtn.onclick = clearPlot;
                document.getElementById('plotSearchBox').appendChild(clearBtn);
            }
        }

        function clearPlot() {
            plotIdInput.value = '';
            plotSearch.value = '';
            document.getElementById('plotPreview').style.display = 'none';
            document.getElementById('total_price').value = '';
            const clearBtn = document.querySelector('#plotSearchBox .clear-btn');
            if (clearBtn) clearBtn.remove();
            calculateBalance();
        }

        // Buyer Search
        const buyerSearch = document.getElementById('buyerSearch');
        const buyerResults = document.getElementById('buyerResults');
        const buyerIdInput = document.getElementById('buyer_id');

        buyerSearch.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const query = this.value.trim();

            if (query.length < 1) {
                buyerResults.classList.remove('show');
                return;
            }

            searchTimeout = setTimeout(() => {
                fetch(`${SITE_URL}/ajax/search-buyers.php?q=${encodeURIComponent(query)}`)
                    .then(r => r.json())
                    .then(data => {
                        if (data.success && data.results.length > 0) {
                            buyerResults.innerHTML = data.results.map(buyer => `
                                <div class="autocomplete-item" onclick="selectBuyer(${buyer.id}, '${escapeHtml(buyer.full_name)}', '${escapeHtml(buyer.phone)}')">
                                    <div class="item-main">${escapeHtml(buyer.full_name)}</div>
                                    <div class="item-sub">${escapeHtml(buyer.phone)}${buyer.email ? ' | ' + escapeHtml(buyer.email) : ''}</div>
                                </div>
                            `).join('');
                        } else {
                            buyerResults.innerHTML = '<div class="autocomplete-empty">No buyers found. <a href="../buyers/create.php?redirect=sale">Add new buyer</a></div>';
                        }
                        buyerResults.classList.add('show');
                    });
            }, 300);
        });

        buyerSearch.addEventListener('focus', function() {
            if (this.value.trim().length >= 1) {
                this.dispatchEvent(new Event('input'));
            }
        });

        function selectBuyer(id, name, phone) {
            buyerIdInput.value = id;
            buyerSearch.value = `${name} (${phone})`;
            buyerResults.classList.remove('show');

            // Update preview
            document.getElementById('previewBuyerName').textContent = name;
            document.getElementById('previewBuyerPhone').textContent = phone;
            document.getElementById('buyerPreview').style.display = 'block';

            // Add clear button
            let clearBtn = document.querySelector('#buyerSearchBox .clear-btn');
            if (!clearBtn) {
                clearBtn = document.createElement('button');
                clearBtn.type = 'button';
                clearBtn.className = 'clear-btn';
                clearBtn.innerHTML = '<i class="fas fa-times"></i>';
                clearBtn.onclick = clearBuyer;
                document.getElementById('buyerSearchBox').appendChild(clearBtn);
            }
        }

        function clearBuyer() {
            buyerIdInput.value = '';
            buyerSearch.value = '';
            document.getElementById('buyerPreview').style.display = 'none';
            const clearBtn = document.querySelector('#buyerSearchBox .clear-btn');
            if (clearBtn) clearBtn.remove();
        }

        // Close dropdowns when clicking outside
        document.addEventListener('click', function(e) {
            if (!e.target.closest('.autocomplete-wrapper')) {
                plotResults.classList.remove('show');
                buyerResults.classList.remove('show');
            }
        });

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function toggleInstallments() {
            const isInstallment = document.querySelector('input[name="payment_type"]:checked').value === 'installment';
            document.querySelectorAll('.installment-field').forEach(el => {
                el.style.display = isInstallment ? 'block' : 'none';
            });
            document.querySelectorAll('.installment-info').forEach(el => {
                el.style.display = isInstallment ? 'flex' : 'none';
            });
            calculateBalance();
        }

        function calculateBalance() {
            const total = parseFloat(document.getElementById('total_price').value) || 0;
            const deposit = parseFloat(document.getElementById('deposit_amount').value) || 0;
            const months = parseInt(document.getElementById('installment_months').value) || 1;
            const isInstallment = document.querySelector('input[name="payment_type"]:checked').value === 'installment';

            const balance = total - deposit;
            const monthly = isInstallment && months > 0 ? balance / months : 0;

            document.getElementById('summaryTotal').textContent = 'TZS ' + formatNumber(total);
            document.getElementById('summaryDeposit').textContent = 'TZS ' + formatNumber(deposit);
            document.getElementById('summaryBalance').textContent = 'TZS ' + formatNumber(balance);
            document.getElementById('summaryMonthly').textContent = 'TZS ' + formatNumber(monthly);

            document.getElementById('paymentSummary').style.display = total > 0 ? 'block' : 'none';
        }

        function formatNumber(num) {
            return Math.round(num).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            toggleInstallments();
            calculateBalance();
        });
    </script>
</body>
</html>
