<?php
include "../db.php";

/* SEARCH */
$search = $_GET['search'] ?? "";

$sql = "SELECT id, name, phone, email, created_at FROM users";
$params = [];

if ($search !== "") {
    $sql .= " WHERE name LIKE ? OR email LIKE ? OR phone LIKE ?";
    $params = ["%$search%", "%$search%", "%$search%"];
}

$sql .= " ORDER BY id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>View Users</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
:root{
    --primary:#0b4f27;
    --primary-dark:#083a1d;
    --bg:#f3f4f6;
    --card:#ffffff;
    --text:#1f2937;
}

body{
    font-family:'Poppins',sans-serif;
    background:var(--bg);
}

.page-title{
    color:var(--primary);
    font-weight:600;
}

.card{
    background:var(--card);
    border-radius:14px;
    border:none;
    box-shadow:0 8px 20px rgba(0,0,0,.06);
}

.table thead th{
    background:#e9f5ef;
    color:#064e3b;
    font-size:13px;
    text-transform:uppercase;
}

.table td{
    color:var(--text);
}

.search-box input{
    border-radius:8px;
}

.btn-primary{
    background:var(--primary);
    border:none;
}
.btn-primary:hover{
    background:var(--primary-dark);
}
</style>
</head>

<body>

<div class="container-fluid p-4">

<div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="page-title mb-0">Users</h3>

    <form class="d-flex"
          onsubmit="window.parent.loadPage('view_users.php?search='+this.search.value); return false;">
        <input type="text" name="search"
               class="form-control form-control-sm me-2"
               placeholder="Search name / email / phone"
               value="<?= htmlspecialchars($search) ?>">
        <button class="btn btn-sm btn-outline-secondary me-2">Search</button>
        <button class="btn btn-sm btn-secondary"
                onclick="window.parent.loadPage('view_users.php'); return false;">
            Reset
        </button>
    </form>
</div>

<div class="card">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr>
    <th>ID</th>
    <th>Name</th>
    <th>Phone</th>
    <th>Email</th>
    <th>Created At</th>
</tr>
</thead>
<tbody>

<?php if(!$users): ?>
<tr>
    <td colspan="5" class="text-center text-muted py-4">
        No users found
    </td>
</tr>
<?php endif; ?>

<?php foreach($users as $u): ?>
<tr>
    <td><?= $u['id'] ?></td>
    <td><?= htmlspecialchars($u['name']) ?></td>
    <td><?= htmlspecialchars($u['phone']) ?></td>
    <td><?= htmlspecialchars($u['email']) ?></td>
    <td><?= $u['created_at'] ?></td>
</tr>
<?php endforeach; ?>

</tbody>
</table>
</div>
</div>

</div>

</body>
</html>
