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

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

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

function formatMoney($amount) {
    return "₱" . number_format((float)($amount ?? 0), 2);
}

$shopId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$selectedType = isset($_GET['service_type']) ? trim($_GET['service_type']) : '';

if ($shopId <= 0) {
    echo "<div class='alert alert-danger'>Invalid shop.</div>";
    exit;
}

/*
|--------------------------------------------------------------------------
| GET SHOP INFO
|--------------------------------------------------------------------------
*/
$shopStmt = $conn->prepare("
    SELECT *
    FROM users
    WHERE id = ?
    AND role = 'admin'
    LIMIT 1
");

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

$shopStmt->bind_param("i", $shopId);
$shopStmt->execute();
$shopResult = $shopStmt->get_result();
$shop = $shopResult->fetch_assoc();

if (!$shop) {
    echo "<div class='alert alert-danger'>Shop not found.</div>";
    exit;
}

/*
|--------------------------------------------------------------------------
| GET AVERAGE RATING
|--------------------------------------------------------------------------
*/
$ratingStmt = $conn->prepare("
    SELECT 
        COALESCE(AVG(feedback_rating), 0) AS average_rating,
        COUNT(feedback_rating) AS rating_count
    FROM orders
    WHERE shop_id = ?
    AND feedback_rating IS NOT NULL
");

$averageRating = 0;
$ratingCount = 0;

if ($ratingStmt) {
    $ratingStmt->bind_param("i", $shopId);
    $ratingStmt->execute();
    $ratingResult = $ratingStmt->get_result()->fetch_assoc();

    $averageRating = (float)($ratingResult["average_rating"] ?? 0);
    $ratingCount = (int)($ratingResult["rating_count"] ?? 0);
}

function renderStars($rating) {
    $rating = (float)$rating;
    $fullStars = floor($rating);
    $halfStar = ($rating - $fullStars) >= 0.5;
    $emptyStars = 5 - $fullStars - ($halfStar ? 1 : 0);

    $html = "";

    for ($i = 0; $i < $fullStars; $i++) {
        $html .= '<i class="fa-solid fa-star"></i>';
    }

    if ($halfStar) {
        $html .= '<i class="fa-solid fa-star-half-stroke"></i>';
    }

    for ($i = 0; $i < $emptyStars; $i++) {
        $html .= '<i class="fa-regular fa-star"></i>';
    }

    return $html;
}

/*
|--------------------------------------------------------------------------
| GET SERVICES
|--------------------------------------------------------------------------
*/
if ($selectedType === '') {
    $servicesStmt = $conn->prepare("
        SELECT s1.id, s1.service_type, s1.service_image, s1.description
        FROM services s1
        INNER JOIN (
            SELECT service_type, MIN(id) AS first_service_id
            FROM services
            WHERE owner_shop_id = ?
            AND status = 'active'
            AND service_type IS NOT NULL
            AND service_type != ''
            GROUP BY service_type
        ) s2 ON s1.id = s2.first_service_id
        WHERE s1.owner_shop_id = ?
        AND s1.status = 'active'
        ORDER BY s1.service_type ASC
    ");

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

    $servicesStmt->bind_param("ii", $shopId, $shopId);
    $servicesStmt->execute();
    $services = $servicesStmt->get_result();
} else {
    $servicesStmt = $conn->prepare("
        SELECT *
        FROM services
        WHERE owner_shop_id = ?
        AND status = 'active'
        AND service_type = ?
        ORDER BY created_at DESC
    ");

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

    $servicesStmt->bind_param("is", $shopId, $selectedType);
    $servicesStmt->execute();
    $services = $servicesStmt->get_result();
}

$shopName = $shop["shop_name"] ?? $shop["business_name"] ?? "Unnamed Shop";
$shopType = $shop["shop_type"] ?? "Not specified";
?>

<div class="container-fluid px-0 shop-details-page">

    <div class="shop-hero-card shadow-sm mb-4">
        <div class="row g-4 align-items-center">
            <div class="col-lg-8">
                <a href="customer.php?page=view-shops" class="back-link mb-3">
                    <i class="fa-solid fa-arrow-left me-1"></i> Back to Shops
                </a>

                <div class="d-flex align-items-center gap-3 flex-wrap mb-3">
                    <div class="shop-avatar">
                        <?php if (!empty($shop["shop_image"])): ?>
                            <img 
                                src="../uploads/shops/<?php echo h($shop["shop_image"]); ?>" 
                                alt="Shop Image"
                                onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
                            >
                            <div class="shop-avatar-placeholder d-none">
                                <i class="fa-solid fa-store"></i>
                            </div>
                        <?php else: ?>
                            <div class="shop-avatar-placeholder">
                                <i class="fa-solid fa-store"></i>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div>
                        <h1 class="fw-bold mb-1"><?php echo h($shopName); ?></h1>
                        <div class="d-flex align-items-center flex-wrap gap-2">
                            <span class="badge rounded-pill bg-primary-subtle text-primary border border-primary-subtle px-3 py-2">
                                <?php echo h(ucfirst($shopType)); ?>
                            </span>

                            <span class="shop-rating">
                                <?php echo renderStars($averageRating); ?>
                            </span>

                            <span class="text-muted small">
                                <?php if ($ratingCount > 0): ?>
                                    <?php echo number_format($averageRating, 1); ?>/5 from <?php echo $ratingCount; ?> feedback
                                <?php else: ?>
                                    No rating yet
                                <?php endif; ?>
                            </span>
                        </div>
                    </div>
                </div>

                <p class="text-muted mb-0 hero-description">
                    Browse available services from this shop and proceed with your order.
                </p>
            </div>

            <div class="col-lg-4">
                <div class="quick-info-card">
                    <div class="quick-info-item">
                        <span class="quick-icon">
                            <i class="fa-solid fa-briefcase"></i>
                        </span>
                        <div>
                            <small>Shop Type</small>
                            <strong><?php echo h(ucfirst($shopType)); ?></strong>
                        </div>
                    </div>

                    <div class="quick-info-item">
                        <span class="quick-icon">
                            <i class="fa-solid fa-star"></i>
                        </span>
                        <div>
                            <small>Rating</small>
                            <strong>
                                <?php echo $ratingCount > 0 ? number_format($averageRating, 1) . "/5" : "No rating"; ?>
                            </strong>
                        </div>
                    </div>

                    <div class="quick-info-item">
                        <span class="quick-icon">
                            <i class="fa-solid fa-list-check"></i>
                        </span>
                        <div>
                            <small>Viewing</small>
                            <strong>
                                <?php echo $selectedType === '' ? "Service Types" : h($selectedType); ?>
                            </strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="services-section-card shadow-sm">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
            <div>
                <?php if ($selectedType === ''): ?>
                    <h2 class="fw-bold mb-1">Available Services</h2>
                    <p class="text-muted mb-0">Choose a service category to view available options.</p>
                <?php else: ?>
                    <h2 class="fw-bold mb-1"><?php echo h($selectedType); ?> Services</h2>
                    <p class="text-muted mb-0">Select a specific service and place your order.</p>
                <?php endif; ?>
            </div>

            <?php if ($selectedType !== ''): ?>
                <a href="customer.php?page=shop_view-details&id=<?php echo $shopId; ?>" class="btn btn-light border rounded-pill px-4">
                    <i class="fa-solid fa-arrow-left me-1"></i> Back to Categories
                </a>
            <?php endif; ?>
        </div>

        <?php if ($services && $services->num_rows > 0): ?>
            <div class="row g-4">

                <?php if ($selectedType === ''): ?>
                    <?php while ($service = $services->fetch_assoc()): ?>
                        <div class="col-12 col-sm-6 col-lg-4 col-xl-3">
                            <div class="service-card-modern h-100">
                                <div class="service-image-box">
                                    <?php if (!empty($service["service_image"])): ?>
                                        <img 
                                            src="../uploads/services/<?php echo h($service["service_image"]); ?>" 
                                            alt="Service Image"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
                                        >
                                        <div class="no-service-image d-none">
                                            <i class="fa-solid fa-image"></i>
                                        </div>
                                    <?php else: ?>
                                        <div class="no-service-image">
                                            <i class="fa-solid fa-image"></i>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div class="service-card-body">
                                    <div class="service-content">
                                        <span class="service-badge">Category</span>

                                        <h3><?php echo h($service["service_type"] ?? "Unnamed Type"); ?></h3>

                                        <p>
                                            <strong>Description:</strong>
                                            <?php echo h($service["description"] ?? "No description available"); ?>
                                        </p>
                                    </div>

                                    <div class="service-actions">
                                        <a 
                                            href="customer.php?page=shop_view-details&id=<?php echo $shopId; ?>&service_type=<?php echo urlencode($service['service_type']); ?>" 
                                            class="btn btn-outline-dark rounded-pill px-3"
                                        >
                                            View Services
                                        </a>

                                        <a 
                                            href="customer.php?page=customer-order-now&shop_id=<?php echo $shopId; ?>" 
                                            class="btn btn-primary rounded-pill px-3"
                                        >
                                            Order Now
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>

                <?php else: ?>
                    <?php while ($service = $services->fetch_assoc()): ?>
                        <div class="col-12 col-sm-6 col-lg-4 col-xl-3">
                            <div class="service-card-modern h-100">
                                <div class="service-image-box">
                                    <?php if (!empty($service["service_image"])): ?>
                                        <img 
                                            src="../uploads/services/<?php echo h($service["service_image"]); ?>" 
                                            alt="Service Image"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
                                        >
                                        <div class="no-service-image d-none">
                                            <i class="fa-solid fa-image"></i>
                                        </div>
                                    <?php else: ?>
                                        <div class="no-service-image">
                                            <i class="fa-solid fa-image"></i>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div class="service-card-body">
                                    <div class="service-content">
                                        <span class="service-badge">Service</span>

                                        <h3><?php echo h($service["service_name"] ?? "Unnamed Service"); ?></h3>

                                        <p>
                                            <strong>Description:</strong>
                                            <?php echo h($service["description"] ?? "No description available"); ?>
                                        </p>

                                        <div class="service-meta">
                                            <div>
                                                <small>Price</small>
                                                <strong><?php echo formatMoney($service["price"] ?? 0); ?></strong>
                                            </div>

                                            <div>
                                                <small>Minimum Order</small>
                                                <strong><?php echo h($service["min_order_quantity"] ?? 1); ?></strong>
                                            </div>

                                            <div>
                                                <small>Estimated Days</small>
                                                <strong><?php echo h($service["estimated_days"] ?? "N/A"); ?></strong>
                                            </div>

                                            <?php if (!empty($service["size"])): ?>
                                                <div>
                                                    <small>Size</small>
                                                    <strong><?php echo h($service["size"]); ?></strong>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="service-actions">
                                        <a 
                                            href="customer.php?page=customer-create-order&shop_id=<?php echo (int)$shop['id']; ?>&service_id=<?php echo (int)$service['id']; ?>" 
                                            class="btn btn-primary rounded-pill w-100"
                                        >
                                            <i class="fa-solid fa-cart-plus me-1"></i> Order This Service
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php endif; ?>

            </div>
        <?php else: ?>
            <div class="empty-service-card">
                <i class="fa-solid fa-box-open"></i>
                <h5>No active services available</h5>
                <p class="text-muted mb-0">This shop has no active services at the moment.</p>
            </div>
        <?php endif; ?>
    </div>

</div>

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

.shop-hero-card,
.services-section-card {
    background: #ffffff;
    border-radius: 24px;
    padding: 28px;
}

.back-link {
    display: inline-flex;
    align-items: center;
    text-decoration: none;
    color: #24324d;
    font-weight: 700;
}

.back-link:hover {
    color: #111827;
}

.shop-details-page h1 {
    font-size: clamp(34px, 3vw, 48px);
    color: #111827;
}

.hero-description {
    font-size: 15px;
    max-width: 650px;
}

.shop-avatar {
    width: 92px;
    height: 92px;
    border-radius: 24px;
    overflow: hidden;
    background: #e5e7eb;
    flex-shrink: 0;
    box-shadow: 0 8px 24px rgba(0,0,0,0.10);
}

.shop-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.shop-avatar-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #facc15, #f97316);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 38px;
}

.shop-rating {
    color: #facc15;
    font-size: 15px;
    letter-spacing: -1px;
}

.quick-info-card {
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 20px;
    padding: 18px;
    display: grid;
    gap: 14px;
}

.quick-info-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.quick-icon {
    width: 42px;
    height: 42px;
    border-radius: 14px;
    background: #24324d;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.quick-info-item small {
    display: block;
    color: #6b7280;
    font-size: 12px;
}

.quick-info-item strong {
    display: block;
    color: #111827;
    font-size: 15px;
}

.services-section-card h2 {
    font-size: 28px;
    color: #111827;
}

.service-card-modern {
    background: #ffffff;
    border: 1px solid #eef0f4;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 8px 22px rgba(0,0,0,0.06);
    transition: 0.2s ease;
    display: flex;
    flex-direction: column;
}

.service-card-modern:hover {
    transform: translateY(-4px);
    box-shadow: 0 14px 34px rgba(0,0,0,0.10);
}

.service-image-box {
    width: 100%;
    height: 260px;
    background: #f3f4f6;
    overflow: hidden;
}

.service-image-box img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    background: #f3f4f6;
    padding: 10px;
}

.no-service-image {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #e5e7eb, #f8fafc);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #9ca3af;
    font-size: 42px;
}

.service-card-body {
    padding: 18px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.service-content {
    flex: 1;
}

.service-badge {
    display: inline-flex;
    margin-bottom: 10px;
    background: #eff6ff;
    color: #2563eb;
    border: 1px solid #bfdbfe;
    border-radius: 999px;
    padding: 5px 12px;
    font-size: 12px;
    font-weight: 700;
}

.service-card-body h3 {
    font-size: 22px;
    font-weight: 800;
    color: #111827;
    margin-bottom: 10px;
    line-height: 1.15;
}

.service-card-body p {
    font-size: 14px;
    line-height: 1.45;
    color: #374151;
}

.service-meta {
    display: grid;
    grid-template-columns: 1fr;
    gap: 8px;
    margin-top: 12px;
}

.service-meta div {
    background: #f8fafc;
    border: 1px solid #eef0f4;
    border-radius: 14px;
    padding: 10px 12px;
}

.service-meta small {
    display: block;
    color: #6b7280;
    font-size: 11px;
}

.service-meta strong {
    display: block;
    color: #111827;
    font-size: 14px;
}

.service-actions {
    margin-top: auto;
    padding-top: 16px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.service-actions .btn {
    font-weight: 700;
}

.btn-primary {
    background: #24324d;
    border-color: #24324d;
}

.btn-primary:hover {
    background: #111827;
    border-color: #111827;
}

.empty-service-card {
    min-height: 260px;
    background: #f8fafc;
    border: 1px dashed #cbd5e1;
    border-radius: 22px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6b7280;
    text-align: center;
}

.empty-service-card i {
    font-size: 46px;
    color: #9ca3af;
    margin-bottom: 12px;
}

@media (max-width: 768px) {
    .shop-hero-card,
    .services-section-card {
        padding: 20px;
        border-radius: 20px;
    }

    .shop-avatar {
        width: 76px;
        height: 76px;
        border-radius: 20px;
    }

    .service-image-box {
        height: 190px;
    }

    .service-actions .btn {
        width: 100%;
    }
}
</style>