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

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

if (!isset($_SESSION["user_id"])) {
    header("Location: index.php");
    exit();
}

$shop_id = (int)$_SESSION["user_id"];

function h($value) {
    return htmlspecialchars($value ?? "", ENT_QUOTES, "UTF-8");
}

function getCount($conn, $sql, $shop_id) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $shop_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        return (int)$row["total"];
    }

    return 0;
}

function formatStatus($status) {
    return ucwords(str_replace("_", " ", $status));
}

function statusBadgeClass($status) {
    $status = strtolower($status ?? "");

    if ($status === "pending") {
        return "bg-warning-subtle text-warning-emphasis";
    }

    if ($status === "accepted") {
        return "bg-info-subtle text-info";
    }

    if ($status === "in_progress") {
        return "bg-primary-subtle text-primary";
    }

    if ($status === "completed") {
        return "bg-success-subtle text-success";
    }

    if ($status === "cancelled") {
        return "bg-danger-subtle text-danger";
    }

    return "bg-secondary-subtle text-secondary";
}

function formatDate($date) {
    if (empty($date) || $date === "0000-00-00") {
        return "N/A";
    }

    return date("M d, Y", strtotime($date));
}

/* =========================
   DASHBOARD COUNTS
========================= */

$totalOrders = getCount($conn, "
    SELECT COUNT(*) AS total
    FROM orders
    WHERE shop_id = ?
", $shop_id);

$activeOrders = getCount($conn, "
    SELECT COUNT(*) AS total
    FROM orders
    WHERE shop_id = ?
    AND status IN ('pending', 'accepted', 'in_progress')
", $shop_id);

$completedOrders = getCount($conn, "
    SELECT COUNT(*) AS total
    FROM orders
    WHERE shop_id = ?
    AND status = 'completed'
", $shop_id);

$totalServices = getCount($conn, "
    SELECT COUNT(*) AS total
    FROM services
    WHERE owner_shop_id = ?
    AND status = 'active'
", $shop_id);

$totalCustomers = getCount($conn, "
    SELECT COUNT(DISTINCT customer_mobile) AS total
    FROM orders
    WHERE shop_id = ?
    AND customer_mobile IS NOT NULL
    AND customer_mobile != ''
", $shop_id);

/* =========================
   RECENT ORDERS
========================= */

$recentOrders = [];

$stmt = $conn->prepare("
    SELECT 
        order_code,
        customer_name,
        service_type,
        item_name,
        status,
        due_date,
        created_at
    FROM orders
    WHERE shop_id = ?
    ORDER BY created_at DESC
    LIMIT 5
");

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

while ($row = $result->fetch_assoc()) {
    $recentOrders[] = $row;
}
?>

<div class="dashboard-content container-fluid px-0">

    <!-- WELCOME CARD -->
    <div class="dashboard-welcome-card mb-4">
        <div>
            <h2 class="fw-bold mb-2">
                Welcome, <?php echo h($_SESSION["shop_name"] ?? "Admin"); ?>!
            </h2>
            <p class="text-muted mb-0">
                Here is a quick overview of your shop activity.
            </p>
        </div>

     <div class="welcome-illustration">
    <img src="/taiprint/html/images/CUSTOMER.png?v=1" alt="Welcome Illustration">
</div>
    </div>

    <!-- STATS CARDS -->
    <div class="row g-3 mb-4">

        <div class="col-12 col-sm-6 col-xl-3">
            <div class="dashboard-stat-card">
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="fa-solid fa-receipt"></i>
                </div>

                <div>
                    <p>Total Orders</p>
                    <h3><?php echo $totalOrders; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-3">
            <div class="dashboard-stat-card">
                <div class="stat-icon bg-info-subtle text-info">
                    <i class="fa-solid fa-spinner"></i>
                </div>

                <div>
                    <p>Active Orders</p>
                    <h3><?php echo $activeOrders; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-3">
            <div class="dashboard-stat-card">
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div>
                    <p>Completed Orders</p>
                    <h3><?php echo $completedOrders; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-3">
            <div class="dashboard-stat-card">
                <div class="stat-icon bg-warning-subtle text-warning-emphasis">
                    <i class="fa-solid fa-users"></i>
                </div>

                <div>
                    <p>Customers</p>
                    <h3><?php echo $totalCustomers; ?></h3>
                </div>
            </div>
        </div>

    </div>

    <!-- QUICK SUMMARY -->
    <div class="row g-3 mb-4">

        <div class="col-12 col-md-6">
            <div class="quick-card">
                <div>
                    <h5 class="fw-bold mb-1">Services</h5>
                    <p class="text-muted mb-0">Active services offered by your shop.</p>
                </div>

                <div class="quick-number">
                    <?php echo $totalServices; ?>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6">
            <div class="quick-card">
                <div>
                    <h5 class="fw-bold mb-1">Manage Orders</h5>
                    <p class="text-muted mb-0">Create, update, and monitor customer orders.</p>
                </div>

                <a href="admin.php?page=orders" class="btn btn-dark rounded-pill px-4">
                    Open
                </a>
            </div>
        </div>

    </div>

    <!-- RECENT ORDERS -->
    <div class="dashboard-table-card">
        <div class="table-card-header">
            <div>
                <h4 class="fw-bold mb-1">Recent Orders</h4>
                <p class="text-muted mb-0">Latest customer orders from your shop.</p>
            </div>

            <a href="admin.php?page=orders" class="btn btn-outline-primary rounded-pill px-4">
                View All
            </a>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle dashboard-table mb-0">
                <thead>
                    <tr>
                        <th>Order Code</th>
                        <th>Customer</th>
                        <th>Service</th>
                        <th>Item</th>
                        <th>Status</th>
                        <th>Due Date</th>
                    </tr>
                </thead>

                <tbody>
                    <?php if (!empty($recentOrders)): ?>
                        <?php foreach ($recentOrders as $order): ?>
                            <tr>
                                <td class="fw-semibold">
                                    <?php echo h($order["order_code"]); ?>
                                </td>

                                <td>
                                    <?php echo h($order["customer_name"] ?: "N/A"); ?>
                                </td>

                                <td>
                                    <?php echo h($order["service_type"] ?: "N/A"); ?>
                                </td>

                                <td>
                                    <?php echo h($order["item_name"] ?: "N/A"); ?>
                                </td>

                                <td>
                                    <span class="badge rounded-pill <?php echo statusBadgeClass($order["status"]); ?>">
                                        <?php echo h(formatStatus($order["status"])); ?>
                                    </span>
                                </td>

                                <td>
                                    <?php echo h(formatDate($order["due_date"])); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6">
                                <div class="empty-state">
                                    <i class="fa-solid fa-clipboard-list"></i>
                                    <p class="mb-0">No recent orders yet.</p>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>

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

</div>

<style>
.dashboard-content {
    width: 100%;
    min-height: auto;
    overflow: visible;
}

.dashboard-welcome-card {
    background: #fff;
    border-radius: 22px;
    padding: 28px 32px;
    box-shadow: 0 6px 20px rgba(0,0,0,0.06);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20px;
}

.dashboard-welcome-card h2 {
    font-size: 30px;
    color: #111827;
}

.welcome-illustration {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.welcome-illustration img {
    width: 260px;
    max-width: 100%;
    height: auto;
    object-fit: contain;
    display: block;
}

.dashboard-stat-card {
    background: #fff;
    border-radius: 18px;
    padding: 22px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    gap: 16px;
    height: 100%;
}

.stat-icon {
    width: 54px;
    height: 54px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    flex-shrink: 0;
}

.dashboard-stat-card p {
    margin: 0 0 4px;
    color: #6b7280;
    font-size: 14px;
}

.dashboard-stat-card h3 {
    margin: 0;
    font-size: 30px;
    font-weight: 800;
    color: #111827;
}

.quick-card {
    background: #fff;
    border-radius: 18px;
    padding: 22px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
    height: 100%;
}

.quick-number {
    min-width: 58px;
    height: 58px;
    border-radius: 18px;
    background: #f3f4f6;
    color: #111827;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;
    font-weight: 800;
}

.dashboard-table-card {
    background: #fff;
    border-radius: 22px;
    padding: 24px;
    box-shadow: 0 6px 20px rgba(0,0,0,0.06);
    overflow-x: auto;
}

.table-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    margin-bottom: 18px;
}

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

.dashboard-table tbody td {
    padding: 14px;
    font-size: 14px;
    border-bottom: 1px solid #f0f0f0;
}

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

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

@media (max-width: 768px) {
    .welcome-illustration {
        width: 100%;
        justify-content: center;
        margin-top: 10px;
    }

    .dashboard-welcome-card h2 {
        font-size: 24px;
    }

     .welcome-illustration img {
        width: 180px;
    }
}

    .table-card-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .quick-card {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>