<?php
require_once("../php/db_connect.php");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$shop_id = $_SESSION["user_id"] ?? 0;
$message = $_GET["message"] ?? "";

if ($shop_id == 0) {
    echo "<script>window.location='index.php';</script>";
    exit;
}

/*
|--------------------------------------------------------------------------
| GET DISTINCT CUSTOMERS FROM ORDERS OF THIS SHOP
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT 
        customer_id,
        MAX(customer_name) AS customer_name,
        MAX(customer_email) AS customer_email,
        MAX(customer_mobile) AS customer_mobile,
        MAX(created_at) AS last_order_date,
        COUNT(*) AS total_orders
    FROM orders
    WHERE shop_id = ?
      AND customer_id IS NOT NULL
    GROUP BY customer_id
    ORDER BY last_order_date DESC
");

$stmt->bind_param("i", $shop_id);
$stmt->execute();
$customers = $stmt->get_result();

/*
|--------------------------------------------------------------------------
| COUNT DISTINCT CUSTOMERS
|--------------------------------------------------------------------------
*/
$countStmt = $conn->prepare("
    SELECT COUNT(DISTINCT customer_id) AS total_customers
    FROM orders
    WHERE shop_id = ?
      AND customer_id IS NOT NULL
");

$countStmt->bind_param("i", $shop_id);
$countStmt->execute();
$countResult = $countStmt->get_result();
$totalCustomers = $countResult->fetch_assoc()["total_customers"] ?? 0;
?>

<div class="container-fluid px-0 user-management-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">User Management</h1>
            <p class="text-muted mb-0">
                Total Customer: <?php echo (int)$totalCustomers; ?>
            </p>
        </div>
    </div>

    <?php if ($message === "archived"): ?>
        <div class="alert alert-success rounded-3">
            Customer archived successfully.
        </div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm rounded-4 user-table-card">
        <div class="card-body p-0">

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 user-table">
                    <thead>
                        <tr>
                            <th>Full Name</th>
                            <th>Email</th>
                            <th>Contact Number</th>
                            <th>Total Orders</th>
                            <th>Last Order Date</th>
                            <th>Status</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if ($customers && $customers->num_rows > 0): ?>
                            <?php while ($row = $customers->fetch_assoc()): ?>
                                <tr>
                                    <td class="fw-semibold">
                                        <?php echo htmlspecialchars($row["customer_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo htmlspecialchars($row["customer_email"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo htmlspecialchars($row["customer_mobile"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <span class="badge bg-primary-subtle text-primary rounded-pill px-3 py-2">
                                            <?php echo (int)$row["total_orders"]; ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?php
                                        echo !empty($row["last_order_date"])
                                            ? htmlspecialchars(date("M d, Y", strtotime($row["last_order_date"])))
                                            : "N/A";
                                        ?>
                                    </td>

                                    <td>
                                        <span class="badge bg-success-subtle text-success rounded-pill px-3 py-2">
                                            Active
                                        </span>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6">
                                    <div class="empty-state">
                                        <i class="fa-solid fa-users"></i>
                                        <p class="mb-0">No customers found.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>

<style>
.user-management-page {
    width: 100%;
    max-width: 100%;
    overflow-x: hidden;
}

.user-management-page h1 {
    font-size: clamp(24px, 2vw, 34px);
    color: #111827;
}

.user-table-card {
    width: 100%;
    max-width: 100%;
    overflow: hidden;
}

.user-table {
    min-width: 850px;
}

.user-table thead th {
    background: #f3f4f6;
    color: #111827;
    font-size: 14px;
    font-weight: 700;
    padding: 16px;
    white-space: nowrap;
    border-bottom: 1px solid #e5e7eb;
}

.user-table tbody td {
    padding: 16px;
    font-size: 14px;
    color: #1f2937;
    border-bottom: 1px solid #f0f0f0;
    white-space: nowrap;
}

.user-table tbody tr:hover {
    background: #f9fbff;
}

.empty-state {
    padding: 40px 10px;
    text-align: center;
    color: #6b7280;
}

.empty-state i {
    font-size: 34px;
    color: #9ca3af;
    margin-bottom: 10px;
}

@media (max-width: 768px) {
    .user-table {
        min-width: 760px;
    }

    .user-table thead th,
    .user-table tbody td {
        padding: 12px;
        font-size: 13px;
    }
}
</style>