<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_users')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

// Delete User Handler
if (isset($_GET['id']) && isset($_GET['del'])) {
    if (!has_permission('manage_users')) {
        $_SESSION['error'] = "You do not have permission to delete users.";
        header('location: registered-users.php');
        exit();
    }
    $id = intval($_GET['id']);
    mysqli_query($con, "delete from user_details where user_id='$id'");
    mysqli_query($con, "delete from users where id='$id'");
    $_SESSION['msg'] = "User deleted successfully";
    header("location:registered-users.php");
    exit;
}
?>

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

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Registered Users - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
        crossorigin="anonymous"></script>


</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-users me-2"></i> Registered Users</h1>
                            <p>View all registered customer accounts</p>
                        </div>
                    </div>

                    <!-- Quick Stats -->
                    <div class="stats-row">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <div class="value">
                                        <?php
                                        $total = mysqli_query($con, "SELECT COUNT(*) as total FROM users WHERE role='customer'");
                                        $totalUsers = mysqli_fetch_assoc($total);
                                        echo $totalUsers['total'];
                                        ?>
                                    </div>
                                    <div class="label">Total Customers</div>
                                </div>
                            </div>

                            <div class="col-md-4 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-user-clock"></i>
                                    </div>
                                    <div class="value">
                                        <?php
                                        $today = mysqli_query($con, "SELECT COUNT(*) as total FROM users WHERE role='customer' AND DATE(regDate) = CURDATE()");
                                        $todayUsers = mysqli_fetch_assoc($today);
                                        echo $todayUsers['total'];
                                        ?>
                                    </div>
                                    <div class="label">New Today</div>
                                </div>
                            </div>

                            <div class="col-md-4 mb-3">
                                <div class="stat-mini">
                                    <div class="icon">
                                        <i class="fas fa-calendar-week"></i>
                                    </div>
                                    <div class="value">
                                        <?php
                                        $week = mysqli_query($con, "SELECT COUNT(*) as total FROM users WHERE role='customer' AND regDate >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
                                        $weekUsers = mysqli_fetch_assoc($week);
                                        echo $weekUsers['total'];
                                        ?>
                                    </div>
                                    <div class="label">This Week</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Users Table -->
                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    <div class="table-card">
                        <table class="table table-hover" id="datatablesSimple">
                            <thead>
                                <tr>
                                    <th width="5%">#</th>
                                    <th>Customer</th>
                                    <th>Email</th>
                                    <th>Contact</th>
                                    <th>Shipping Address</th>
                                    <th>Registration Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $query = mysqli_query($con, "SELECT users.id, users.email, users.regDate, 
                                                              user_details.name, user_details.contactno,
                                                              user_details.shippingAddress, user_details.shippingCity, 
                                                              user_details.shippingState, user_details.shippingPincode
                                                              FROM users 
                                                              LEFT JOIN user_details ON user_details.user_id = users.id
                                                              WHERE users.role = 'customer'
                                                              ORDER BY users.id DESC");
                                $cnt = 1;
                                while ($row = mysqli_fetch_array($query)) {
                                    $initials = substr($row['name'], 0, 2);
                                    ?>
                                    <tr>
                                        <td><?php echo $cnt; ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="user-avatar"><?php echo strtoupper($initials); ?></div>
                                                <strong><?php echo htmlentities($row['name']); ?></strong>
                                            </div>
                                        </td>
                                        <td><?php echo htmlentities($row['email']); ?></td>
                                        <td><?php echo htmlentities($row['contactno']); ?></td>
                                        <td>
                                            <?php
                                            if ($row['shippingAddress']) {
                                                echo htmlentities($row['shippingAddress'] . ', ' . $row['shippingCity'] . ', ' . $row['shippingState'] . ' - ' . $row['shippingPincode']);
                                            } else {
                                                echo '<em style="color: #999;">Not provided</em>';
                                            }
                                            ?>
                                        </td>
                                        <td><?php echo date('M d, Y', strtotime($row['regDate'])); ?></td>
                                        <td>
                                            <a href="edit-user.php?id=<?php echo $row['id']; ?>"
                                                class="btn btn-sm btn-primary me-2" title="Edit"><i
                                                    class="fas fa-edit"></i></a>
                                            <a href="registered-users.php?id=<?php echo $row['id']; ?>&del=delete"
                                                onClick="return confirm('Are you sure you want to delete?')"
                                                class="btn btn-danger btn-sm" title="Delete"><i
                                                    class="fas fa-trash"></i></a>
                                        </td>
                                    </tr>
                                    <?php $cnt++;
                                } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        crossorigin="anonymous"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>