<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/admin/inc/config.php';
require_once __DIR__ . '/data/site.php';
require_once __DIR__ . '/data/contact.php';

/*
|--------------------------------------------------------------------------
| HTML ESCAPE HELPER
|--------------------------------------------------------------------------
*/

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars(
            (string) ($value ?? ''),
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/*
|--------------------------------------------------------------------------
| BASE URL
|--------------------------------------------------------------------------
*/

$baseUrl = rtrim(
    (string) ($site['base_url'] ?? ''),
    '/'
);

/*
|--------------------------------------------------------------------------
| CONTACT PAGE BANNER IMAGE
|--------------------------------------------------------------------------
*/

$bannerImage = trim(
    (string) ($contact_page['banner_image'] ?? '')
);

if ($bannerImage !== '') {
    if (
        !preg_match('~^(https?:)?//~i', $bannerImage) &&
        !preg_match('~^data:~i', $bannerImage)
    ) {
        $bannerImage = $baseUrl . '/' . ltrim($bannerImage, '/');
    }
}

/*
|--------------------------------------------------------------------------
| FETCH ACTIVE LOCATIONS AND THEIR ASSOCIATED CATEGORIES
|--------------------------------------------------------------------------
|
| Supports both:
| 1. Category-level records: sl.category_id is populated.
| 2. Product-level records: sl.service_id is populated.
|
*/

$stmt = $pdo->prepare("
    SELECT DISTINCT
        l.id AS location_id,
        l.location_name,
        l.slug AS location_slug,

        COALESCE(
            category_direct.top_category_name,
            category_product.top_category_name
        ) AS category_name,

        COALESCE(
            category_direct.top_category_slug,
            category_product.top_category_slug
        ) AS category_slug

    FROM tbl_location AS l

    INNER JOIN tbl_service_location AS sl
        ON sl.location_id = l.id

    LEFT JOIN tbl_top_category AS category_direct
        ON category_direct.id = sl.category_id

    LEFT JOIN tbl_service AS s
        ON s.id = sl.service_id

    LEFT JOIN tbl_top_category AS category_product
        ON category_product.id = s.top_category_id

    WHERE l.status = 1

      AND (
          (
              sl.category_id IS NOT NULL
              AND category_direct.status = 1
          )

          OR

          (
              sl.service_id IS NOT NULL
              AND s.status = 1
              AND category_product.status = 1
          )
      )

    ORDER BY
        l.location_name ASC,
        category_name ASC
");

$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| GROUP LOCATIONS BY LOCATION AND CATEGORY
|--------------------------------------------------------------------------
|
| A location can be associated with multiple categories.
| Each location/category combination gets its own card.
|
*/

$locations = [];

foreach ($rows as $row) {
    $locationId = (int) $row['location_id'];

    $locationSlug = trim(
        (string) ($row['location_slug'] ?? '')
    );

    $categorySlug = trim(
        (string) ($row['category_slug'] ?? '')
    );

    // Skip incomplete records.
    if ($locationSlug === '' || $categorySlug === '') {
        continue;
    }

    $key = $locationId . '|' . $categorySlug;

    if (!isset($locations[$key])) {
        $locations[$key] = [
            'id'            => $locationId,
            'name'          => $row['location_name'],
            'slug'          => $locationSlug,
            'category_name' => $row['category_name'],
            'category_slug' => $categorySlug
        ];
    }
}

$locations = array_values($locations);

/*
|--------------------------------------------------------------------------
| HEADER
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/includes/header.php';
?>

<style>
/* =========================================================
   LOCATIONS PAGE
   Responsive location cards
========================================================= */

/* =========================================================
   HERO BANNER
========================================================= */

.locations-hero {
    position: relative;
    min-height: 270px;

    display: flex;
    align-items: center;
    justify-content: center;

    padding: 55px 20px;
    text-align: center;

    background-color: #f7f9fc;

    background-image:
        linear-gradient(
            rgba(255, 255, 255, 0.82),
            rgba(255, 255, 255, 0.88)
        ),
        url("<?= e($bannerImage) ?>");

    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}

.locations-hero-inner {
    position: relative;
    z-index: 1;

    width: 100%;
    max-width: 900px;
    margin: 0 auto;
}

.locations-hero h1 {
    margin: 0;

    color: #14527d;

    font-size: clamp(32px, 4vw, 48px);
    font-weight: 800;
    line-height: 1.2;
}

/* =========================================================
   LOCATION SECTION
========================================================= */

.locations-section {
    padding: 65px 0 85px;
    background: #f7f9fc;
}

.locations-section .container-fluid {
    width: 100%;
    max-width: 1500px;

    margin: 0 auto;
    padding-left: 35px;
    padding-right: 35px;
}

/* =========================================================
   LOCATION GRID
========================================================= */

.locations-grid {
    display: grid;

    grid-template-columns: repeat(4, minmax(0, 1fr));

    gap: 25px;

    align-items: stretch;
}

/* =========================================================
   LOCATION CARD
========================================================= */

.location-card {
    min-width: 0;
    min-height: 200px;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    gap: 16px;

    padding: 28px 18px;

    background: #ffffff;

    border: 1px solid #e8edf3;
    border-radius: 12px;

    box-shadow: 0 5px 20px rgba(18, 46, 75, 0.055);

    text-decoration: none !important;

    transition:
        transform 0.25s ease,
        box-shadow 0.25s ease,
        border-color 0.25s ease;
}

.location-card:hover {
    transform: translateY(-5px);

    border-color: #b9d5ec;

    box-shadow: 0 14px 32px rgba(20, 82, 125, 0.12);
}

/* =========================================================
   LOCATION ICON
========================================================= */

.location-icon {
    width: 64px;
    height: 64px;

    display: flex;
    align-items: center;
    justify-content: center;

    flex-shrink: 0;

    margin: 0;

    color: #145b8c;
    background: #edf6fd;

    border-radius: 50%;
}

.location-icon svg {
    display: block;

    width: 34px;
    height: 34px;
}

/* =========================================================
   LOCATION NAME
========================================================= */

.location-card h2 {
    margin: 0;

    color: #202b38;

    font-size: 20px;
    font-weight: 700;
    line-height: 1.4;

    text-align: center;
    overflow-wrap: anywhere;

    transition: color 0.25s ease;
}

.location-card:hover h2 {
    color: #145b8c;
}

/* =========================================================
   EMPTY STATE
========================================================= */

.locations-empty {
    max-width: 650px;

    margin: 0 auto;
    padding: 45px 25px;

    text-align: center;

    color: #555;
    background: #ffffff;

    border: 1px solid #e8edf3;
    border-radius: 12px;
}

.locations-empty h2 {
    margin: 0 0 12px;

    color: #202b38;

    font-size: 24px;
    font-weight: 700;
}

.locations-empty p {
    margin: 0;

    color: #666;

    font-size: 15px;
    line-height: 1.7;
}

/* =========================================================
   LARGE DESKTOP
========================================================= */

@media (min-width: 1400px) {
    .locations-grid {
        grid-template-columns: repeat(5, minmax(0, 1fr));
    }
}

/* =========================================================
   TABLET
========================================================= */

@media (max-width: 1100px) {
    .locations-grid {
        grid-template-columns: repeat(3, minmax(0, 1fr));
        gap: 20px;
    }

    .location-card {
        min-height: 185px;
    }
}

/* =========================================================
   MOBILE
========================================================= */

@media (max-width: 700px) {
    .locations-hero {
        min-height: 210px;
        padding: 40px 18px;
    }

    .locations-hero h1 {
        font-size: 32px;
    }

    .locations-section {
        padding: 40px 0 55px;
    }

    .locations-section .container-fluid {
        padding-left: 18px;
        padding-right: 18px;
    }

    .locations-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 14px;
    }

    .location-card {
        min-height: 155px;

        gap: 12px;

        padding: 20px 10px;

        border-radius: 10px;
    }

    .location-icon {
        width: 52px;
        height: 52px;
    }

    .location-icon svg {
        width: 29px;
        height: 29px;
    }

    .location-card h2 {
        font-size: 16px;
    }

    .locations-empty {
        padding: 35px 18px;
    }

    .locations-empty h2 {
        font-size: 21px;
    }
}

/* =========================================================
   EXTRA SMALL MOBILE
========================================================= */

@media (max-width: 360px) {
    .locations-grid {
        grid-template-columns: 1fr;
    }

    .location-card {
        min-height: 130px;
    }
}
</style>

<!-- =======================================================
     HERO BANNER
======================================================= -->

<section class="locations-hero">
    <div class="locations-hero-inner">
        <h1>Our Locations</h1>
    </div>
</section>

<!-- =======================================================
     LOCATION CARDS
======================================================= -->

<section class="locations-section">

    <div class="container-fluid">

        <?php if (!empty($locations)): ?>

            <div class="locations-grid">

                <?php foreach ($locations as $location): ?>

                    <?php
                    $locationUrl =
                        $baseUrl . '/' .
                        rawurlencode($location['slug']) . '/' .
                        rawurlencode($location['category_slug']);
                    ?>

                    <a
                        class="location-card"
                        href="<?= e($locationUrl) ?>"
                        aria-label="<?= e(
                            $location['name'] .
                            ' - ' .
                            $location['category_name']
                        ) ?>"
                    >

                        <div class="location-icon">

                            <svg
                                viewBox="0 0 110 110"
                                xmlns="http://www.w3.org/2000/svg"
                                aria-hidden="true"
                                focusable="false"
                            >
                                <path
                                    d="M8 91 L27 60 L42 57
                                       M70 57 L84 60 L103 91
                                       L77 89 L55 96 L32 89 Z"
                                    fill="none"
                                    stroke="#145b8c"
                                    stroke-width="2"
                                    stroke-linejoin="round"
                                />

                                <path
                                    d="M55 8
                                       C37 8 25 22 25 39
                                       C25 59 55 83 55 83
                                       C55 83 85 59 85 39
                                       C85 22 73 8 55 8 Z"
                                    fill="#b8e3fa"
                                    stroke="#145b8c"
                                    stroke-width="2"
                                />

                                <circle
                                    cx="55"
                                    cy="37"
                                    r="19"
                                    fill="#dff3ff"
                                />

                                <circle
                                    cx="55"
                                    cy="37"
                                    r="10"
                                    fill="#ffffff"
                                    stroke="#145b8c"
                                    stroke-width="1.5"
                                />
                            </svg>

                        </div>

                        <h2>
                            <?= e($location['name']) ?>
                        </h2>

                    </a>

                <?php endforeach; ?>

            </div>

        <?php else: ?>

            <div class="locations-empty">

                <h2>No locations available</h2>

                <p>
                    Active locations associated with active categories
                    or products will appear here.
                </p>

            </div>

        <?php endif; ?>

    </div>

</section>

<!-- =======================================================
     FOOTER
======================================================= -->

<?php require_once __DIR__ . '/includes/footer.php'; ?>
