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

$agency_id = $_SESSION['agency_id'];
$search = $_GET['search'] ?? '';

// 1. Fetch Queries (Using LEFT JOIN so manual names show up too)
$query_sql = "SELECT q.*, c.name as db_client_name, c.phone_number as db_phone 
              FROM queries q 
              LEFT JOIN clients c ON q.client_id = c.id 
              WHERE q.agency_id = $agency_id";

if(!empty($search)) {
    $search_like = "%$search%";
    $query_sql .= " AND (c.name LIKE '$search_like' OR q.manual_name LIKE '$search_like')";
}
$query_sql .= " ORDER BY q.id DESC";
$queries = $conn->query($query_sql);

// 2. Fetch Clients for Autocomplete
$client_list = [];
$clients_res = $conn->query("SELECT id, name, phone_number FROM clients WHERE agency_id = $agency_id");
while($row = $clients_res->fetch_assoc()){ $client_list[] = $row; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Enquiry Management | Travel SaaS</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; --secondary: #1e293b; --bg: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px; }
        .sidebar { width: 260px; background: var(--secondary); height: 100vh; position: fixed; color: #fff; padding: 20px 0; top:0; left:0; }
        .nav-link { display: flex; align-items: center; padding: 12px 15px; color: rgba(255,255,255,0.7); text-decoration: none; border-radius: 8px; margin: 5px 20px; }
        .active { background: rgba(255,255,255,0.1); color: #fff; }
        .main-content { margin-left: 260px; width: calc(100% - 260px); padding: 0 40px; }
        .card { background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); margin-bottom: 30px; }
        .search-wrapper { position: relative; }
        .results-box { position: absolute; background: white; width: 100%; z-index: 1000; border: 1px solid #ddd; border-radius: 10px; max-height: 200px; 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; }
        label { display: block; font-size: 11px; font-weight: 700; color: #64748b; margin-bottom: 5px; text-transform: uppercase; }
        input, select, textarea { width: 100%; padding: 12px; margin-top: 5px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 14px; }
        .btn { background: var(--primary); color: #fff; padding: 12px 25px; border: none; border-radius: 10px; cursor: pointer; font-weight: 600; margin-top: 15px; }
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 15px; background: #f8f9fc; color: #64748b; font-size: 11px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .badge { padding: 6px 12px; border-radius: 12px; font-size: 11px; font-weight: 600; color: #fff; display: inline-block; }
        .badge-pending { background-color: #f59e0b; }
        .badge-done { background-color: #22c55e; }
        .badge-cancelled { background-color: #ef4444; }
        .badge-progress { background-color: #3b82f6; }
    </style>
</head>
<body>

    <div class="sidebar">
        <div style="padding: 0 25px 30px; font-weight: 600; font-size: 18px;"><i class="fas fa-plane-departure text-primary"></i> TRAVEL SAAS</div>
        <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <a href="clients.php" class="nav-link "><i class="fas fa-users"></i> My Clients</a>
        <a href="queries.php" class="nav-link active"><i class="fas fa-question-circle"></i> Enquiries</a>
        <a href="marketplace.php" class="nav-link"><i class="fas fa-shopping-cart"></i> B2B Marketplace</a>
        <a href="umrah_vouchers.php" class="nav-link"><i class="fas fa-kaaba"></i> Umrah Vouchers</a>
        <a href="ticket_vouchers.php" class="nav-link "><i class="fas fa-ticket-alt"></i> Ticket Vouchers</a>
        <a href="posters.php" class="nav-link"><i class="fas fa-image"></i> Poster Maker</a>
        <a href="ledger.php" class="nav-link"><i class="fas fa-wallet"></i> My Accounts</a>
        <?php if($_SESSION['user_role'] == 'AgencyOwner'): ?>
            <a href="staff.php" class="nav-link"><i class="fas fa-user-tie"></i> Manage Staff</a>
            <a href="agency_profile.php" class="nav-link"><i class="fas fa-cog"></i> Settings</a>
        <?php endif; ?>
        <div style="position: absolute; bottom: 20px; width: 100%;">
            <a href="logout.php" class="nav-link" style="color: #ff7675;"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <div class="main-content">
        <h1>Enquiry Management</h1>
        <div class="card">
            <h3><i class="fas fa-plus-circle"></i> Register New Enquiry</h3>
            <form action="handle_query.php" method="POST">
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px;">
                    <div class="search-wrapper">
                        <label>Client Name</label>
                        <input type="text" name="manual_name" id="client_search" placeholder="Select or type new..." autocomplete="off" required>
                        <input type="hidden" name="client_id" id="client_id_hidden">
                        <div id="results_box" class="results-box"></div>
                    </div>
                    <div>
                        <label>Phone Number (Optional)</label>
                        <input type="text" name="manual_phone" id="client_phone" placeholder="e.g. 03001234567">
                    </div>
                    <div>
                        <label>Service Required</label>
                        <select name="service_type" required>
                            <option value="Umrah">Umrah</option>
                            <option value="Airline Ticket">Airline Ticket</option>
                            <option value="Visit Visa">Visit Visa</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                </div>
                <div style="margin-top: 15px;">
                    <label>Enquiry Details</label>
                    <textarea name="description" rows="3" required placeholder="What are they looking for?"></textarea>
                </div>
                <button type="submit" name="add_query" class="btn">Save Enquiry</button>
            </form>
        </div>

        <div class="card">
            <h3>Recent Enquiries</h3>
            <table>
                <thead>
                    <tr><th>Date</th><th>Client Details</th><th>Service</th><th>Status</th><th>Action</th></tr>
                </thead>
                <tbody>
                    <?php while($row = $queries->fetch_assoc()): 
                        $display_name = !empty($row['db_client_name']) ? $row['db_client_name'] : $row['manual_name'];
                        $display_phone = !empty($row['db_phone']) ? $row['db_phone'] : $row['manual_phone'];
                        
                        $status = strtolower($row['status']);
                        $badgeClass = match ($status) {
                            'pending'     => 'badge-pending',
                            'done'        => 'badge-done',
                            'cancelled'   => 'badge-cancelled',
                            'in process'  => 'badge-progress',
                            default       => 'badge-default',
                        };
                    ?>
                    <tr>
                        <td style="color:#94a3b8; font-size:12px;"><?php echo date('d M, Y', strtotime($row['created_at'])); ?></td>
                        <td>
                            <b><?php echo htmlspecialchars($display_name); ?></b><br>
                            <small style="color:#64748b;"><?php echo $display_phone ?: 'No Phone'; ?></small>
                        </td>
                        <td><b style="color:var(--primary);"><?php echo $row['service_type']; ?></b></td>
                        <td><span class="badge <?php echo $badgeClass; ?>"><?php echo ucfirst($row['status']); ?></span></td>
                        <td><a href="update_query.php?id=<?php echo $row['id']; ?>" style="color:var(--primary); font-weight:600;"><i class="fas fa-edit"></i> Update</a></td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        const clients = <?php echo json_encode($client_list); ?>;
        const searchInput = document.getElementById('client_search');
        const phoneInput = document.getElementById('client_phone');
        const resultsBox = document.getElementById('results_box');
        const hiddenId = document.getElementById('client_id_hidden');

        searchInput.addEventListener('input', function() {
            const val = this.value.toLowerCase();
            resultsBox.innerHTML = '';
            hiddenId.value = ''; 
            if(val.length < 1) { resultsBox.style.display = 'none'; return; }
            const filtered = clients.filter(c => c.name.toLowerCase().includes(val) || c.phone_number.includes(val));
            if(filtered.length > 0) {
                resultsBox.style.display = 'block';
                filtered.forEach(c => {
                    const div = document.createElement('div');
                    div.className = 'result-item';
                    div.innerHTML = `<b>${c.name}</b> - ${c.phone_number}`;
                    div.onclick = function() {
                        searchInput.value = c.name;
                        phoneInput.value = c.phone_number;
                        hiddenId.value = c.id;
                        resultsBox.style.display = 'none';
                    };
                    resultsBox.appendChild(div);
                });
            } else { resultsBox.style.display = 'none'; }
        });
    </script>
</body>
</html>