<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');


if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['phone'];

$successMsg = "";
$errorMsg   = "";

/* ================= USER DATA ================= */

$udata = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'")
);

$type = $udata['type'];

/* ================= ADMIN CHECK ================= */

if ($type != 'admin') {

    die("
    <div style='
        height:100vh;
        display:flex;
        justify-content:center;
        align-items:center;
        background:#f4f7fb;
        font-family:Arial;
    '>

        <div style='
            background:#fff;
            padding:40px;
            border-radius:20px;
            text-align:center;
            box-shadow:0 10px 30px rgba(0,0,0,.1);
        '>

            <h2 style='color:red;'>Access Denied</h2>

            <p>You are not authorized to access this page.</p>

            <a href='dashboard.php'
               style='
                    background:#2563eb;
                    color:#fff;
                    padding:12px 25px;
                    border-radius:10px;
                    text-decoration:none;
                    display:inline-block;
                    margin-top:15px;
               '>
               Back Dashboard
            </a>

        </div>

    </div>
    ");
}

/* ================= RESET PASSWORD ================= */

if (isset($_GET['resetpass'])) {

    $id = intval($_GET['resetpass']);

    $newpass = rand(100000,999999);

    $hashpass = password_hash($newpass, PASSWORD_DEFAULT);

    mysqli_query(
        $ahk_conn,
        "UPDATE users SET password='$hashpass' WHERE id='$id'"
    );

    $successMsg = "New Password : ".$newpass;
}

/* ================= CHANGE STATUS ================= */

if (isset($_GET['status'])) {

    $id = intval($_GET['status']);

    $get = mysqli_fetch_assoc(
        mysqli_query(
            $ahk_conn,
            "SELECT status FROM users WHERE id='$id'"
        )
    );

    $newstatus = ($get['status'] == 1) ? 0 : 1;

    mysqli_query(
        $ahk_conn,
        "UPDATE users SET status='$newstatus' WHERE id='$id'"
    );

    $successMsg = "User status updated successfully";
}

/* ================= DELETE USER ================= */

if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);

    mysqli_query(
        $ahk_conn,
        "DELETE FROM users WHERE id='$id'"
    );

    $successMsg = "User deleted successfully";
}

/* ================= SEARCH ================= */

$search = "";

if (!empty($_GET['search'])) {

    $s = mysqli_real_escape_string($ahk_conn, $_GET['search']);

    $search = "
        AND (
            name LIKE '%$s%' OR
            phone LIKE '%$s%' OR
            email LIKE '%$s%'
        )
    ";
}

/* ================= FETCH USERS ================= */

$users = mysqli_query($ahk_conn, "
    SELECT *
    FROM users
    WHERE 1
    $search
    ORDER BY id DESC
");

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Manage Users</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"/>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{
    background:#eef3fb;
    font-family:'Segoe UI',sans-serif;
}

/* ================= PAGE HEADER ================= */

.page-header{
    background:linear-gradient(135deg,#2563eb,#1d4ed8);
    padding:25px;
    border-radius:22px;
    color:#fff;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(37,99,235,.25);
}

.page-title{
    font-size:30px;
    font-weight:800;
}

.page-subtitle{
    opacity:.9;
    margin-top:5px;
}

/* ================= CARD ================= */

.card-box{
    background:#fff;
    border-radius:22px;
    padding:25px;
    box-shadow:0 10px 25px rgba(0,0,0,.06);
}

/* ================= ADMIN BUTTON ================= */

.admin-btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:#fff;
    color:#2563eb;
    padding:12px 22px;
    border-radius:12px;
    text-decoration:none;
    font-weight:700;
    transition:.3s;
}

.admin-btn:hover{
    transform:translateY(-2px);
    color:#1d4ed8;
}

/* ================= SEARCH ================= */

.search-box .form-control{
    border-radius:12px;
    height:50px;
    border:1px solid #dbe3f0;
}

.search-box .btn{
    border-radius:12px;
    padding:0 25px;
    font-weight:700;
}

/* ================= TABLE ================= */

.table{
    border-radius:15px;
    overflow:hidden;
}

.table thead{
    background:#0f172a;
    color:#fff;
}

.table th{
    padding:15px;
    border:none;
    font-size:14px;
}

.table td{
    padding:15px;
    vertical-align:middle;
    font-size:14px;
}

.table tbody tr:hover{
    background:#f8fbff;
}

/* ================= BADGES ================= */

.user-badge{
    padding:8px 15px;
    border-radius:30px;
    font-size:12px;
    font-weight:700;
}

.active-badge{
    background:#dcfce7;
    color:#166534;
}

.inactive-badge{
    background:#fee2e2;
    color:#991b1b;
}

/* ================= BUTTONS ================= */

.action-btn{
    border:none;
    padding:8px 12px;
    border-radius:10px;
    font-size:12px;
    font-weight:600;
    margin:2px;
    transition:.3s;
}

.action-btn:hover{
    transform:translateY(-2px);
}

/* ================= MOBILE ================= */

@media(max-width:768px){

    .page-title{
        font-size:24px;
    }

    .table td,
    .table th{
        white-space:nowrap;
    }

    .action-btn{
        width:100%;
        margin-bottom:5px;
    }
}

</style>

</head>

<body>

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

<!-- ================= HEADER ================= -->

<div class="page-header">

<div class="d-flex justify-content-between align-items-center flex-wrap gap-3">

<div>

<div class="page-title">
<i class="fa-solid fa-users me-2"></i>
Manage Users
</div>

<div class="page-subtitle">
Admin control panel for managing all users
</div>

</div>

<a href="admindash.php" class="admin-btn">

<i class="fa-solid fa-gauge-high"></i>

Back To Admin Panel

</a>

</div>

</div>

<!-- ================= CARD ================= -->

<div class="card-box">

<div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">

<h4 class="fw-bold text-primary mb-0">
All Registered Users
</h4>

<form method="GET" class="d-flex search-box">

<input type="text"
name="search"
class="form-control me-2"
placeholder="Search name, phone or email">

<button class="btn btn-primary">
<i class="fa-solid fa-magnifying-glass"></i>
Search
</button>

</form>

</div>

<div class="table-responsive">

<table class="table table-hover align-middle text-center">

<thead>

<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Type</th>
<th>Balance</th>
<th>Status</th>
<th width="280">Actions</th>
</tr>

</thead>

<tbody>

<?php if(mysqli_num_rows($users) > 0): ?>

<?php while($u = mysqli_fetch_assoc($users)): ?>

<tr>

<td>
<b>#<?= $u['id'] ?></b>
</td>

<td>
<?= htmlspecialchars($u['name']) ?>
</td>

<td>
<?= htmlspecialchars($u['phone']) ?>
</td>

<td>
<?= htmlspecialchars($u['email']) ?>
</td>

<td>

<span class="badge bg-primary px-3 py-2">

<?= strtoupper($u['type']) ?>

</span>

</td>

<td>

<b class="text-success">
₹<?= number_format($u['balance'],2) ?>
</b>

</td>

<td>

<?php if($u['status'] == 1){ ?>

<span class="user-badge active-badge">
Active
</span>

<?php } else { ?>

<span class="user-badge inactive-badge">
Inactive
</span>

<?php } ?>

</td>

<td>

<!-- PASSWORD -->

<a href="?resetpass=<?= $u['id'] ?>"
class="btn btn-warning action-btn"
onclick="return confirm('Reset password?')">

<i class="fa-solid fa-key"></i>

Password

</a>

<!-- STATUS -->

<a href="?status=<?= $u['id'] ?>"
class="btn btn-info text-white action-btn">

<i class="fa-solid fa-toggle-on"></i>

Status

</a>

<!-- BALANCE -->

<a href="../balancetr.php?user=<?= $u['phone'] ?>"
class="btn btn-success action-btn">

<i class="fa-solid fa-wallet"></i>

Balance

</a>

<!-- DELETE -->

<a href="?delete=<?= $u['id'] ?>"
class="btn btn-danger action-btn"
onclick="return confirm('Delete this user?')">

<i class="fa-solid fa-trash"></i>

Delete

</a>

</td>

</tr>

<?php endwhile; ?>

<?php else: ?>

<tr>

<td colspan="8">

<div class="py-4 text-muted">
No Users Found
</div>

</td>

</tr>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

</div>

<?php if($successMsg): ?>

<script>

Swal.fire({
    icon:'success',
    title:'Success',
    text:<?= json_encode($successMsg) ?>
});

</script>

<?php endif; ?>

<?php if($errorMsg): ?>

<script>

Swal.fire({
    icon:'error',
    title:'Error',
    text:<?= json_encode($errorMsg) ?>
});

</script>

<?php endif; ?>

<?php include('footer.php'); ?>

</body>
</html>