<?php 
include 'config.php'; 
if(!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'SuperAdmin') { 
    header("Location: dashboard.php"); exit(); 
}

// 1. Fetch All Agencies for the Search Tool
$agency_list = [];
$agency_res = $conn->query("SELECT id, agency_name, phone, balance_due FROM agencies WHERE id > 1 ORDER BY agency_name ASC");
while($row = $agency_res->fetch_assoc()){
    $agency_list[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Record Agency Payment | Super Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #4e73df; --success: #1cc88a; --bg: #f8f9fc; }
        body { font-family: 'Poppins', sans-serif; background-color: var(--bg); padding: 50px; }
        .form-card { background: #fff; max-width: 650px; margin: auto; padding: 40px; border-radius: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.05); border-top: 5px solid var(--success); }
        .header { text-align: center; margin-bottom: 30px; }
        
        /* Autocomplete Search Styles */
        .search-wrapper { position: relative; margin-bottom: 20px; }
        .results-box { 
            position: absolute; background: white; width: 100%; z-index: 1000; 
            border: 1px solid #ddd; border-radius: 10px; max-height: 250px; 
            overflow-y: auto; display: none; box-shadow: 0 10px 25px rgba(0,0,0,0.1); 
        }
        .result-item { padding: 12px 15px; cursor: pointer; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .result-item:hover { background: #f8f9fc; }
        .result-item b { color: var(--primary); }

        label { display: block; font-size: 13px; font-weight: 600; color: #64748b; margin-bottom: 8px; text-transform: uppercase; }
        input, select, textarea { width: 100%; padding: 12px; margin-bottom: 5px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 14px; box-sizing: border-box; }
        
        .agency-info-box { background: #f0fff4; border: 1px solid #c6f6d5; padding: 15px; border-radius: 12px; margin-bottom: 20px; display: none; }
        .bal-val { color: #2f855a; font-size: 18px; font-weight: 700; }

        .btn-submit { background: var(--success); color: white; border: none; padding: 15px; width: 100%; border-radius: 10px; font-weight: 700; cursor: pointer; font-size: 16px; margin-top: 20px; transition: 0.3s; }
        .btn-submit:hover { background: #169b6b; transform: translateY(-2px); }
    </style>
</head>
<body>

    <div class="form-card">
        <div class="header">
            <i class="fas fa-money-check-alt" style="font-size: 40px; color: var(--success); margin-bottom: 10px;"></i>
            <h2>Credit Agency Account</h2>
            <p style="color:#64748b;">Search and record payments received from agencies.</p>
        </div>

        <form action="handle_saas_payment.php" method="POST">
            
            <label>1. Search Agency (Name or Phone)</label>
            <div class="search-wrapper">
                <input type="text" id="agency_search" placeholder="Type Agency Name or Phone Number..." autocomplete="off" required>
                <input type="hidden" name="agency_id" id="agency_id_hidden">
                <div id="results_box" class="results-box"></div>
            </div>

            <!-- Dynamic Agency Details -->
            <div id="agency_details" class="agency-info-box">
                <div style="display:flex; justify-content: space-between; align-items: center;">
                    <div>
                        <small style="color:#64748b; text-transform:uppercase; font-size:10px;">Current Balance Due</small><br>
                        <span class="bal-val" id="disp_bal">PKR 0</span>
                    </div>
                    <div style="text-align:right;">
                        <small style="color:#64748b; text-transform:uppercase; font-size:10px;">Agency Phone</small><br>
                        <b id="disp_phone">-</b>
                    </div>
                </div>
            </div>

            <label>2. Amount Received (PKR)</label>
            <input type="number" name="amount" placeholder="Enter amount received" required>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px;">
                <div>
                    <label>Payment Method</label>
                    <select name="method">
                        <option>Bank Transfer</option>
                        <option>JazzCash</option>
                        <option>EasyPaisa</option>
                        <option>Cash</option>
                        <option>Other</option>
                    </select>
                </div>
                <div>
                    <label>Transaction ID</label>
                    <input type="text" name="transaction_id" placeholder="Optional Ref #">
                </div>
            </div>

            <label style="margin-top: 15px;">3. Payment Notes</label>
            <textarea name="notes" rows="2" placeholder="e.g. Received for January 2026 Subscription Fee"></textarea>

            <button type="submit" class="btn-submit">Record & Update Balance</button>
            <a href="saas_revenue.php" style="display:block; text-align:center; margin-top:15px; color:#64748b; text-decoration:none; font-size:13px;">Go Back</a>
        </form>
    </div>

    <!-- AUTOCOMPLETE JAVASCRIPT -->
    <script>
        const agencies = <?php echo json_encode($agency_list); ?>;
        const searchInput = document.getElementById('agency_search');
        const resultsBox = document.getElementById('results_box');
        const hiddenId = document.getElementById('agency_id_hidden');
        
        // UI Display Elements
        const detailsBox = document.getElementById('agency_details');
        const dispBal = document.getElementById('disp_bal');
        const dispPhone = document.getElementById('disp_phone');

        searchInput.addEventListener('input', function() {
            const val = this.value.toLowerCase();
            resultsBox.innerHTML = '';
            
            if(val.length < 1) { 
                resultsBox.style.display = 'none'; 
                return; 
            }

            const filtered = agencies.filter(a => 
                a.agency_name.toLowerCase().includes(val) || a.phone.includes(val)
            );

            if(filtered.length > 0) {
                resultsBox.style.display = 'block';
                filtered.forEach(a => {
                    const div = document.createElement('div');
                    div.className = 'result-item';
                    div.innerHTML = `<b>${a.agency_name}</b> - ${a.phone}`;
                    div.onclick = function() {
                        // Fill Form
                        searchInput.value = a.agency_name;
                        hiddenId.value = a.id;
                        
                        // Show Stats
                        detailsBox.style.display = 'block';
                        dispBal.innerText = "PKR " + Number(a.balance_due).toLocaleString();
                        dispPhone.innerText = a.phone;
                        
                        resultsBox.style.display = 'none';
                    };
                    resultsBox.appendChild(div);
                });
            } else {
                resultsBox.style.display = 'none';
            }
        });

        // Hide results when clicking outside
        document.addEventListener('click', function (e) {
            if (!searchInput.contains(e.target) && !resultsBox.contains(e.target)) {
                resultsBox.style.display = 'none';
            }
        });
    </script>
</body>
</html>