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

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

$shop_id = isset($_SESSION["user_id"]) ? (int)$_SESSION["user_id"] : 0;
$message = $_GET["message"] ?? "";

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

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

$stmt = $conn->prepare("
    SELECT 
        s.*,
        variant_data.variants,
        variant_data.min_price,
        variant_data.max_price
    FROM services s
    LEFT JOIN (
        SELECT 
            service_id,
            MIN(price) AS min_price,
            MAX(price) AS max_price,
            GROUP_CONCAT(
                CONCAT(size, ' - ₱', FORMAT(price, 2))
                ORDER BY FIELD(size, 'XS', 'S', 'M', 'L', 'XL', '2XL', '3XL'), size
                SEPARATOR '||'
            ) AS variants
        FROM service_variants
        WHERE is_available = 1
        GROUP BY service_id
    ) AS variant_data
        ON s.id = variant_data.service_id
    WHERE s.owner_shop_id = ?
      AND s.status != 'archived'
    ORDER BY s.created_at DESC
");

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

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

$countStmt = $conn->prepare("
    SELECT COUNT(*) AS total_services
    FROM services
    WHERE owner_shop_id = ?
      AND status != 'archived'
");

if (!$countStmt) {
    die("Prepare failed: " . $conn->error);
}

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

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

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

    if ($status === "inactive") {
        return "bg-secondary-subtle text-secondary border border-secondary-subtle";
    }

    return "bg-light text-dark border";
}

function formatPriceRange($minPrice, $maxPrice) {
    if ($minPrice === null || $maxPrice === null || $minPrice === "" || $maxPrice === "") {
        return "-";
    }

    if ((float)$minPrice === (float)$maxPrice) {
        return "₱" . number_format((float)$minPrice, 2);
    }

    return "₱" . number_format((float)$minPrice, 2) . " - ₱" . number_format((float)$maxPrice, 2);
}
?>

<div class="container-fluid px-0 service-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">Service Management</h1>
            <p class="text-muted mb-0">
                Total Services: <?php echo (int)$totalServices; ?>
            </p>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <a href="admin.php?page=add-service" class="btn btn-primary rounded-pill px-4">
                <i class="fa-solid fa-plus me-1"></i> Add Service
            </a>

            <a href="admin.php?page=service-types" class="btn btn-light border rounded-pill px-4">
                Manage Service Types
            </a>

           <a href="admin.php?page=archived-services" class="btn btn-outline-dark rounded-pill px-4">
    View Archived
</a>
        </div>
    </div>

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

<?php if ($message === "added"): ?>

<script>
Swal.fire({
    icon: 'success',
    title: 'Service Added!',
    text: 'Service added successfully.',
    confirmButtonText: 'OK',
    confirmButtonColor: '#16a34a',
    background: '#ffffff',
    color: '#111827',
    iconColor: '#16a34a',
    width: 470,
    customClass: {
        popup: 'rounded-4 shadow-lg'
    }
});
</script>

<?php elseif ($message === "updated"): ?>

<script>
Swal.fire({
    icon: 'success',
    title: 'Service Updated!',
    text: 'Service updated successfully.',
    confirmButtonText: 'OK',
    confirmButtonColor: '#16a34a',
    background: '#ffffff',
    color: '#111827',
    iconColor: '#16a34a',
    width: 470,
    customClass: {
        popup: 'rounded-4 shadow-lg'
    }
});
</script>

<?php elseif ($message === "archived"): ?>

<script>
Swal.fire({
    icon: 'success',
    title: 'Service Archived!',
    text: 'Service archived successfully.',
    confirmButtonText: 'OK',
    confirmButtonColor: '#16a34a',
    background: '#ffffff',
    color: '#111827',
    iconColor: '#16a34a',
    width: 470,
    customClass: {
        popup: 'rounded-4 shadow-lg'
    }
});
</script>

<?php elseif ($message === "shop_image_updated"): ?>

<script>
Swal.fire({
    icon: 'success',
    title: 'Updated!',
    text: 'Shop image updated successfully.',
    confirmButtonText: 'OK',
    confirmButtonColor: '#16a34a',
    background: '#ffffff',
    color: '#111827',
    iconColor: '#16a34a',
    width: 470,
    customClass: {
        popup: 'rounded-4 shadow-lg'
    }
});
</script>

<?php elseif ($message === "error"): ?>

<script>
Swal.fire({
    icon: 'error',
    title: 'Oops!',
    text: 'Something went wrong.',
    confirmButtonText: 'OK',
    confirmButtonColor: '#dc2626',
    background: '#ffffff',
    color: '#111827',
    width: 470,
    customClass: {
        popup: 'rounded-4 shadow-lg'
    }
});
</script>

<?php endif; ?>

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

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 service-table">
                    <thead>
                        <tr>
                            <th>Image</th>
                            <th>Service Name</th>
                            <th>Service Type</th>
                            <th>Sizes & Prices</th>
                            <th>Price Range</th>
                            <th>Min Qty</th>
                            <th>Days</th>
                            <th>Status</th>
                            <th>Featured</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if ($services && $services->num_rows > 0): ?>
                            <?php while ($row = $services->fetch_assoc()): ?>

                                <?php
                                $variants = [];

                                if (!empty($row["variants"])) {
                                    $variants = explode("||", $row["variants"]);
                                }

                                if (empty($variants) && !empty($row["size"]) && !empty($row["price"])) {
                                    $variants[] = $row["size"] . " - ₱" . number_format((float)$row["price"], 2);
                                    $row["min_price"] = $row["price"];
                                    $row["max_price"] = $row["price"];
                                }

                                $priceRange = formatPriceRange($row["min_price"], $row["max_price"]);

                                $imagePath = !empty($row["service_image"])
                                    ? "../uploads/services/" . h($row["service_image"])
                                    : "";
                                ?>

                                <tr>
                                    <td>
                                        <?php if (!empty($imagePath)): ?>
                                            <img 
                                                src="<?php echo $imagePath; ?>" 
                                                alt="Service Image"
                                                class="service-img"
                                            >
                                        <?php else: ?>
                                            <div class="service-img-placeholder">
                                                <i class="fa-solid fa-image"></i>
                                            </div>
                                        <?php endif; ?>
                                    </td>

                                    <td class="fw-semibold service-name">
                                        <?php echo h($row["service_name"]); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["service_type"]); ?>
                                    </td>

                                    <td>
                                        <?php if (!empty($variants)): ?>
                                            <div class="variant-list">
                                                <?php foreach ($variants as $variant): ?>
                                                    <span class="variant-badge">
                                                        <?php echo h($variant); ?>
                                                    </span>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted small">No sizes added</span>
                                        <?php endif; ?>
                                    </td>

                                    <td class="fw-semibold">
                                        <?php echo h($priceRange); ?>
                                    </td>

                                    <td>
                                        <?php echo (int)$row["min_order_quantity"]; ?>
                                    </td>

                                    <td>
                                        <?php echo (int)$row["estimated_days"]; ?> day(s)
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill px-3 py-2 <?php echo statusBadgeClass($row["status"]); ?>">
                                            <?php echo h(ucfirst($row["status"])); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?php if ((int)$row["is_featured"] === 1): ?>
                                            <span class="badge bg-warning-subtle text-warning-emphasis rounded-pill px-3 py-2">
                                                Yes
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-light text-dark border rounded-pill px-3 py-2">
                                                No
                                            </span>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <div class="d-flex flex-column flex-sm-row gap-2">
                                            <a 
                                                href="admin.php?page=edit-service&id=<?php echo (int)$row['id']; ?>" 
                                                class="btn btn-sm btn-outline-primary"
                                            >
                                                Edit
                                            </a>

                                           <a 
    href="archive-service.php?id=<?php echo (int)$service['id']; ?>" 
    class="btn btn-outline-danger btn-sm"
    onclick="return confirm('Are you sure you want to archive this service?');"
>
    Archive
</a>
                                        </div>
                                    </td>
                                </tr>

                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="10">
                                    <div class="empty-state">
                                        <i class="fa-solid fa-scissors"></i>
                                        <h5 class="fw-bold mb-1">No services found</h5>
                                        <p class="text-muted mb-3">
                                            Add your first service to start offering products to customers.
                                        </p>

                                        <a href="admin.php?page=add-service" class="btn btn-primary rounded-pill px-4">
                                            Add Service
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>

                </table>
            </div>

        </div>
    </div>

</div>

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

.service-management-page h1 {
    font-size: clamp(26px, 2.2vw, 38px);
    color: #111827;
}

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

.service-table {
    min-width: 1120px;
}

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

.service-table tbody td {
    padding: 16px;
    font-size: 14px;
    color: #1f2937;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

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

.service-name {
    min-width: 150px;
    max-width: 220px;
    white-space: normal;
}

.service-img,
.service-img-placeholder {
    width: 64px;
    height: 64px;
    border-radius: 14px;
    flex-shrink: 0;
}

.service-img {
    object-fit: cover;
    border: 1px solid #e5e7eb;
}

.service-img-placeholder {
    background: #f3f4f6;
    color: #9ca3af;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    border: 1px solid #e5e7eb;
}

.variant-list {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    min-width: 220px;
    max-width: 360px;
}

.variant-badge {
    background: #e0f2fe;
    color: #075985;
    border: 1px solid #bae6fd;
    padding: 5px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 600;
    white-space: nowrap;
}

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

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

@media (max-width: 992px) {
    .service-table {
        min-width: 1050px;
    }

    .service-table thead th,
    .service-table tbody td {
        padding: 14px;
        font-size: 13px;
    }
}

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

    .service-img,
    .service-img-placeholder {
        width: 54px;
        height: 54px;
        border-radius: 12px;
    }

    .variant-list {
        max-width: 300px;
    }
}
</style>