<?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 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;
}

$search = trim($_GET['search'] ?? '');

$sql = "
    SELECT 
        u.*,
        GROUP_CONCAT(DISTINCT s.service_type ORDER BY s.service_type SEPARATOR ', ') AS services_list,
        COALESCE(AVG(o.feedback_rating), 0) AS average_rating,
        COUNT(o.feedback_rating) AS rating_count
    FROM users u
    LEFT JOIN services s 
        ON s.owner_shop_id = u.id 
        AND s.status = 'active'
    LEFT JOIN orders o
        ON o.shop_id = u.id
        AND o.feedback_rating IS NOT NULL
    WHERE u.role = 'admin'
";

$params = [];
$types = '';

if (!empty($search)) {
    $words = array_filter(explode(' ', $search));

    foreach ($words as $word) {
        $sql .= "
            AND (
                u.shop_name LIKE ?
                OR u.business_name LIKE ?
                OR u.shop_type LIKE ?
                OR s.service_name LIKE ?
                OR s.service_type LIKE ?
            )
        ";

        $like = "%{$word}%";
        array_push($params, $like, $like, $like, $like, $like);
        $types .= "sssss";
    }
}

$sql .= "
    GROUP BY u.id
    ORDER BY u.created_at DESC
";

$stmt = $conn->prepare($sql);

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

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$shops = $stmt->get_result();
$totalShops = $shops ? $shops->num_rows : 0;
?>

<div class="container-fluid px-0 view-shops-page">

    <div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">View Shops</h1>
            <p class="text-muted mb-0">
                Find available tailoring and printing shops for your order.
            </p>
        </div>

        <form method="GET" class="shop-search-form d-flex gap-2">
            <input type="hidden" name="page" value="view-shops">

            <input
                type="text"
                name="search"
                class="form-control"
                placeholder="Search shops or services..."
                value="<?php echo h($search); ?>"
            >

            <button type="submit" class="btn btn-primary px-4">
                Search
            </button>
        </form>
    </div>

    <div class="shop-hub-card shadow-sm border-0">

        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
            <div>
                <h4 class="fw-bold mb-1">Find Partner</h4>
                <p class="text-muted mb-0">
                    Total Available Shops: <?php echo $totalShops; ?>
                </p>
            </div>

            <div class="d-flex gap-2">
                <button type="button" class="carousel-nav-btn" onclick="scrollShopsLeft()">
                    <i class="fa-solid fa-chevron-left"></i>
                </button>

                <button type="button" class="carousel-nav-btn" onclick="scrollShopsRight()">
                    <i class="fa-solid fa-chevron-right"></i>
                </button>
            </div>
        </div>

        <div class="shops-carousel-wrap">

            <button type="button" class="side-scroll-btn left-btn" onclick="scrollShopsLeft()">
                <i class="fa-solid fa-chevron-left"></i>
            </button>

            <div class="shops-carousel" id="shopsCarousel">

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

                        <?php
                        $shopName = $row["shop_name"] ?? $row["business_name"] ?? "Unnamed Shop";
                        $shopType = $row["shop_type"] ?? "Not specified";

                        $servicesText = !empty($row["services_list"])
                            ? $row["services_list"]
                            : "No services listed";

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

                        <div class="shop-card-modern">

                            <div class="shop-image-box">
                                <?php if (!empty($row["shop_image"])): ?>
                                    <img 
                                        src="../uploads/shops/<?php echo h($row["shop_image"]); ?>" 
                                        alt="Shop Image"
                                        onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
                                    >
                                    <div class="no-shop-image d-none">
                                        <i class="fa-solid fa-store"></i>
                                    </div>
                                <?php else: ?>
                                    <div class="no-shop-image">
                                        <i class="fa-solid fa-store"></i>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="shop-card-content">
                                <h3><?php echo h($shopName); ?></h3>

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

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

                                <p class="mb-1">
                                    <strong>Shop Type:</strong>
                                    <?php echo h(ucfirst($shopType)); ?>
                                </p>

                                <p class="shop-specialty mb-3">
                                    <strong>Specialty:</strong>
                                    <?php echo h($servicesText); ?>
                                </p>
                            </div>

                            <div class="shop-card-footer">
                                <a 
                                    href="customer.php?page=shop_view-details&id=<?php echo (int)$row['id']; ?>" 
                                    class="btn btn-outline-dark rounded-pill px-4"
                                >
                                    View Details
                                </a>
                            </div>

                        </div>

                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="no-shops-found">
                        <i class="fa-solid fa-store-slash mb-2"></i>
                        <h5>No shops available.</h5>
                        <p class="text-muted mb-0">Try searching another shop or service.</p>
                    </div>
                <?php endif; ?>

            </div>

            <button type="button" class="side-scroll-btn right-btn" onclick="scrollShopsRight()">
                <i class="fa-solid fa-chevron-right"></i>
            </button>

        </div>
    </div>

</div>

<script>
function scrollShopsLeft() {
    const carousel = document.getElementById("shopsCarousel");
    carousel.scrollBy({
        left: -320,
        behavior: "smooth"
    });
}

function scrollShopsRight() {
    const carousel = document.getElementById("shopsCarousel");
    carousel.scrollBy({
        left: 320,
        behavior: "smooth"
    });
}
</script>

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

.view-shops-page h1 {
    font-size: clamp(30px, 3vw, 46px);
    color: #111827;
}

.shop-search-form {
    width: min(100%, 420px);
}

.shop-search-form .form-control {
    min-width: 260px;
    border-radius: 10px;
    padding: 12px 14px;
}

.shop-search-form .btn {
    border-radius: 10px;
    background: #24324d;
    border-color: #24324d;
    font-weight: 700;
}

.shop-hub-card {
    background: #f3f4f6;
    border-radius: 22px;
    padding: 28px;
    position: relative;
    overflow: hidden;
}

.shops-carousel-wrap {
    position: relative;
}

.shops-carousel {
    display: flex;
    align-items: stretch;
    gap: 28px;
    overflow-x: auto;
    scroll-behavior: smooth;
    padding: 8px 12px 24px;
}

.shops-carousel::-webkit-scrollbar {
    height: 10px;
}

.shops-carousel::-webkit-scrollbar-track {
    background: #e5e7eb;
    border-radius: 999px;
}

.shops-carousel::-webkit-scrollbar-thumb {
    background: #9ca3af;
    border-radius: 999px;
}

.shop-card-modern {
    min-width: 260px;
    max-width: 260px;
    min-height: 375px;
    background: #ffffff;
    border-radius: 10px;
    padding: 22px;
    box-shadow: 0 8px 22px rgba(0, 0, 0, 0.06);
    transition: 0.2s ease;

    display: flex;
    flex-direction: column;
}

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

.shop-image-box {
    width: 100%;
    height: 150px;
    border-radius: 8px;
    overflow: hidden;
    background: #e5e7eb;
    margin-bottom: 18px;
    flex-shrink: 0;
}

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

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

.shop-card-content {
    flex: 1;
}

.shop-card-content h3 {
    font-size: 22px;
    font-weight: 800;
    color: #111827;
    margin-bottom: 8px;
    line-height: 1.1;
    min-height: 48px;
}

.shop-rating {
    min-height: 24px;
}

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

.shop-rating .rating-text {
    color: #6b7280;
    font-size: 14px;
    margin-left: 4px;
}

.shop-card-content p {
    color: #111827;
    font-size: 14px;
    line-height: 1.35;
}

.shop-specialty {
    min-height: 40px;
}

.shop-card-footer {
    margin-top: auto;
    padding-top: 18px;
}

.shop-card-footer .btn {
    min-width: 150px;
    font-weight: 600;
}

.carousel-nav-btn {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    border: 1px solid #d1d5db;
    background: #ffffff;
    color: #111827;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.carousel-nav-btn:hover {
    background: #24324d;
    color: #ffffff;
}

.side-scroll-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 5;
    width: 42px;
    height: 42px;
    border-radius: 50%;
    border: 1px solid #d1d5db;
    background: #ffffff;
    color: #374151;
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
    display: flex;
    align-items: center;
    justify-content: center;
}

.side-scroll-btn:hover {
    background: #24324d;
    color: #ffffff;
}

.left-btn {
    left: -10px;
}

.right-btn {
    right: -10px;
}

.no-shops-found {
    width: 100%;
    min-height: 220px;
    background: #ffffff;
    border-radius: 18px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6b7280;
}

.no-shops-found i {
    font-size: 42px;
    color: #9ca3af;
}

@media (max-width: 768px) {
    .shop-hub-card {
        padding: 20px;
    }

    .shop-search-form {
        width: 100%;
    }

    .shop-search-form .form-control {
        min-width: 0;
        width: 100%;
    }

    .shop-card-modern {
        min-width: 230px;
        max-width: 230px;
        min-height: 370px;
        padding: 18px;
    }

    .shop-image-box {
        height: 130px;
    }

    .side-scroll-btn {
        display: none;
    }
}
</style>