<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ================= ADD GUEST =================
if(isset($_POST['add_guest'])){
    $name  = trim($_POST['name']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $idno  = trim($_POST['id_number']);

    // Check for duplicates
    $check = $conn->prepare("SELECT * FROM guests WHERE phone=? OR email=? OR id_number=?");
    $check->bind_param("sss", $phone, $email, $idno);
    $check->execute();
    $result = $check->get_result();

    if($result->num_rows > 0){
        echo "<script>alert('Guest with this phone, email, or ID already exists');</script>";
    } else {
        $stmt = $conn->prepare("INSERT INTO guests (name, phone, email, id_number, status) VALUES (?,?,?,?,1)");
        $stmt->bind_param("ssss", $name, $phone, $email, $idno);
        $stmt->execute();
        echo "<script>alert('Guest added and pending approval');window.location='guests.php';</script>";
    }
}

// ================= QUICK APPROVE =================
if(isset($_GET['approve_id'])){
    $approve_id = intval($_GET['approve_id']);
    $conn->query("UPDATE guests SET status=2 WHERE id=$approve_id"); // 2 = Approved
    echo "<script>window.location='guests.php';</script>";
}

// ================= DELETE GUEST =================
if(isset($_GET['delete_id'])){
    $delete_id = intval($_GET['delete_id']);
    $conn->query("DELETE FROM guests WHERE id=$delete_id");
    echo "<script>window.location='guests.php';</script>";
}

// ================= PAGINATION & SEARCH =================
$search = trim($_GET['search'] ?? '');
$page   = intval($_GET['page'] ?? 1);
$limit  = 10; // guests per page
$offset = ($page - 1) * $limit;

$where = "";
$params = [];
$param_types = "";

if($search !== ""){
    $where = "WHERE name LIKE ? OR phone LIKE ? OR email LIKE ? OR id_number LIKE ?";
    $like = "%$search%";
    $params = [$like, $like, $like, $like];
    $param_types = "ssss";
}

// Count total records
$count_sql = "SELECT COUNT(*) as total FROM guests $where";
$stmt_count = $conn->prepare($count_sql);
if($search !== ""){
    $stmt_count->bind_param($param_types, ...$params);
}
$stmt_count->execute();
$total = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total / $limit);

// Fetch paginated records
$sql = "SELECT * FROM guests $where ORDER BY id DESC LIMIT ?, ?";
$stmt = $conn->prepare($sql);

if($search !== ""){
    $all_params = array_merge($params, [$offset, $limit]);
    $all_types  = $param_types . "ii";

    $bind_names[] = $all_types;
    for ($i=0; $i<count($all_params); $i++) {
        $bind_name = 'bind' . $i;
        $$bind_name = $all_params[$i];
        $bind_names[] = &$$bind_name; // references required
    }
    call_user_func_array([$stmt, 'bind_param'], $bind_names);

} else {
    $stmt->bind_param("ii", $offset, $limit);
}

$stmt->execute();
$guests = $stmt->get_result();

// ================= COLLECT DUPLICATES =================
$duplicate_keys = [];
$all_rows = $guests->fetch_all(MYSQLI_ASSOC);

// Build a map to detect duplicates within the current page
$seen = ['phone'=>[], 'email'=>[], 'id_number'=>[]];
foreach($all_rows as $row){
    foreach(['phone','email','id_number'] as $key){
        if($row[$key] !== '' && isset($seen[$key][$row[$key]])){
            // mark duplicates
            $duplicate_keys[$row['id']] = true;
            $duplicate_keys[$seen[$key][$row[$key]]] = true;
        }
        $seen[$key][$row[$key]] = $row['id'];
    }
}

// Rewind pointer to iterate
$guests->data_seek(0);
?>

<div class="container mt-4">
    <?php $username = $_SESSION['username'] ?? 'Guest'; ?>
    <div class="welcome-msg mb-3">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>

    <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h4>Guest Management</h4><hr>

    <!-- ================= SEARCH ================= -->
    <form method="GET" class="mb-3 row g-2">
        <div class="col-md-4">
            <input type="text" name="search" class="form-control" placeholder="Search guests..." value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary w-100">Search</button>
        </div>
    </form>

    <!-- ================= ADD GUEST ================= -->
    
    <form method="POST" class="row g-2 mb-3">
        <div class="col-md-3"><input name="name" class="form-control" placeholder="Guest Name" required></div>
        <div class="col-md-2"><input name="phone" class="form-control" placeholder="Phone"></div>
        <div class="col-md-3"><input name="email" class="form-control" placeholder="Email"></div>
        <div class="col-md-2"><input name="id_number" class="form-control" placeholder="ID/Passport"></div>
        <div class="col-md-2"><button name="add_guest" class="btn btn-success w-100">Add Guest</button></div>
    </form>

    <!-- ================= GUESTS TABLE ================= -->
    <table class="table table-bordered table-sm">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>ID</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php $i = $offset + 1; while($g = $guests->fetch_assoc()): ?>
            <?php 
                $row_class = isset($duplicate_keys[$g['id']]) ? 'table-danger' : '';
            ?>
            <tr class="<?= $row_class ?>">
                <td><?= $i++ ?></td>
                <td><?= htmlspecialchars($g['name']) ?></td>
                <td><?= htmlspecialchars($g['phone']) ?></td>
                <td><?= htmlspecialchars($g['email']) ?></td>
                <td><?= htmlspecialchars($g['id_number']) ?></td>
                <td>
                    <?= $g['status'] == 1 ? '<span class="badge bg-warning">Pending</span>' : '<span class="badge bg-success">Approved</span>' ?>
                </td>
              <td>
    <?php if($g['status'] == 1): ?>
        <a href="?approve_id=<?= $g['id'] ?>" class="btn btn-sm btn-success">Approve</a>
    <?php endif; ?>

    <?php 
    $user_role = $_SESSION['role'] ?? 'guest'; 
    if(in_array($user_role, ['admin','manager'])): 
    ?>
        <a href="?delete_id=<?= $g['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this guest?')">Delete</a>
    <?php endif; ?>
</td>

            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <!-- ================= PAGINATION LINKS ================= -->
    <nav>
        <ul class="pagination">
            <?php for($p=1; $p<=$total_pages; $p++): ?>
                <li class="page-item <?= $p==$page ? 'active' : '' ?>">
                    <a class="page-link" href="?page=<?= $p ?>&search=<?= urlencode($search) ?>"><?= $p ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
</div>

<?php include 'includes/footer.php'; ?>
