<?php
/**
 * Pure Chemical Admin
 * File: admin/services.php
 *
 * Existing table used:
 * services
 *
 * Columns:
 * id
 * parent_id
 * name
 * slug
 * short_description
 * description
 * icon
 * featured_image_id
 * banner_id
 * status
 * featured
 * sort_order
 * created_at
 * updated_at
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';


/* =========================================================
   AUTH
========================================================= */

if (function_exists('requireAdmin')) {
    requireAdmin();
} else {
    if (
        empty($_SESSION['admin_id']) &&
        empty($_SESSION['admin_logged_in'])
    ) {
        header('Location: login.php');
        exit;
    }
}


/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}


function serviceSlug($text)
{
    $text = trim((string)$text);

    if ($text === '') {
        return '';
    }

    $text = preg_replace('/[^\p{L}\p{N}]+/u', '-', $text);
    $text = trim($text, '-');
    $text = strtolower($text);

    return $text;
}


function redirectServices($params = [])
{
    $url = basename($_SERVER['PHP_SELF']);

    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }

    header('Location: ' . $url);
    exit;
}


/* =========================================================
   CSRF
========================================================= */

if (empty($_SESSION['services_csrf'])) {
    $_SESSION['services_csrf'] = bin2hex(
        random_bytes(32)
    );
}

$csrfToken = $_SESSION['services_csrf'];


function verifyServicesCsrf()
{
    global $csrfToken;

    $token = $_POST['csrf_token'] ?? '';

    if (
        !$token ||
        !hash_equals($csrfToken, $token)
    ) {
        http_response_code(419);
        exit('Invalid or expired security token.');
    }
}


/* =========================================================
   FLASH
========================================================= */

$success =
    $_SESSION['services_success']
    ?? '';

$error =
    $_SESSION['services_error']
    ?? '';

unset($_SESSION['services_success']);
unset($_SESSION['services_error']);


/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';

    try {

        verifyServicesCsrf();


        /* =================================================
           SAVE SERVICE
        ================================================= */

        if ($action === 'save') {

            $id = filter_input(
                INPUT_POST,
                'id',
                FILTER_VALIDATE_INT
            );

            $parentId = filter_input(
                INPUT_POST,
                'parent_id',
                FILTER_VALIDATE_INT
            );

            $name = trim(
                $_POST['name'] ?? ''
            );

            $slug = trim(
                $_POST['slug'] ?? ''
            );

            $shortDescription = trim(
                $_POST['short_description'] ?? ''
            );

            $description = trim(
                $_POST['description'] ?? ''
            );

            $icon = trim(
                $_POST['icon'] ?? ''
            );

            $featuredImageId = filter_input(
                INPUT_POST,
                'featured_image_id',
                FILTER_VALIDATE_INT
            );

            $bannerId = filter_input(
                INPUT_POST,
                'banner_id',
                FILTER_VALIDATE_INT
            );

            $status = isset($_POST['status'])
                ? 1
                : 0;

            $featured = isset($_POST['featured'])
                ? 1
                : 0;

            $sortOrder = filter_input(
                INPUT_POST,
                'sort_order',
                FILTER_VALIDATE_INT
            );


            /* ---------------------------------------------
               VALIDATION
            --------------------------------------------- */

            if ($name === '') {
                throw new Exception(
                    'Service name is required.'
                );
            }

            if (mb_strlen($name) > 255) {
                throw new Exception(
                    'Service name cannot exceed 255 characters.'
                );
            }


            /* Generate slug automatically if empty */

            if ($slug === '') {
                $slug = serviceSlug($name);
            } else {
                $slug = serviceSlug($slug);
            }

            if ($slug === '') {
                throw new Exception(
                    'Please provide a valid service slug.'
                );
            }

            if (mb_strlen($slug) > 255) {
                throw new Exception(
                    'Service slug cannot exceed 255 characters.'
                );
            }


            if ($sortOrder === false || $sortOrder === null) {
                $sortOrder = 0;
            }

            if ($sortOrder < 0) {
                throw new Exception(
                    'Sort order cannot be negative.'
                );
            }


            if (
                $featuredImageId === false ||
                $featuredImageId === null ||
                $featuredImageId < 1
            ) {
                $featuredImageId = null;
            }


            if (
                $bannerId === false ||
                $bannerId === null ||
                $bannerId < 1
            ) {
                $bannerId = null;
            }


            if (
                $parentId === false ||
                $parentId === null ||
                $parentId < 1
            ) {
                $parentId = null;
            }


            /* ---------------------------------------------
               PREVENT SERVICE FROM BEING ITS OWN PARENT
            --------------------------------------------- */

            if (
                $id &&
                $parentId &&
                (int)$id === (int)$parentId
            ) {
                throw new Exception(
                    'A service cannot be its own parent.'
                );
            }


            /* ---------------------------------------------
               VERIFY PARENT EXISTS
            --------------------------------------------- */

            if ($parentId) {

                $stmt = $pdo->prepare("
                    SELECT id
                    FROM services
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $parentId
                ]);

                if (!$stmt->fetchColumn()) {
                    throw new Exception(
                        'Selected parent service does not exist.'
                    );
                }
            }


            /* ---------------------------------------------
               SLUG DUPLICATE CHECK
            --------------------------------------------- */

            if ($id) {

                $stmt = $pdo->prepare("
                    SELECT id
                    FROM services
                    WHERE slug = ?
                      AND id != ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $slug,
                    $id
                ]);

            } else {

                $stmt = $pdo->prepare("
                    SELECT id
                    FROM services
                    WHERE slug = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $slug
                ]);
            }


            if ($stmt->fetchColumn()) {
                throw new Exception(
                    'This service slug is already in use.'
                );
            }


            /* ---------------------------------------------
               UPDATE
            --------------------------------------------- */

            if ($id) {

                $stmt = $pdo->prepare("
                    UPDATE services
                    SET
                        parent_id = ?,
                        name = ?,
                        slug = ?,
                        short_description = ?,
                        description = ?,
                        icon = ?,
                        featured_image_id = ?,
                        banner_id = ?,
                        status = ?,
                        featured = ?,
                        sort_order = ?
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $parentId,
                    $name,
                    $slug,
                    $shortDescription !== ''
                        ? $shortDescription
                        : null,
                    $description !== ''
                        ? $description
                        : null,
                    $icon !== ''
                        ? $icon
                        : null,
                    $featuredImageId,
                    $bannerId,
                    $status,
                    $featured,
                    $sortOrder,
                    $id
                ]);

                $_SESSION['services_success'] =
                    'Service updated successfully.';

                redirectServices();
            }


            /* ---------------------------------------------
               INSERT
            --------------------------------------------- */

            $stmt = $pdo->prepare("
                INSERT INTO services
                (
                    parent_id,
                    name,
                    slug,
                    short_description,
                    description,
                    icon,
                    featured_image_id,
                    banner_id,
                    status,
                    featured,
                    sort_order
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?
                )
            ");

            $stmt->execute([
                $parentId,
                $name,
                $slug,
                $shortDescription !== ''
                    ? $shortDescription
                    : null,
                $description !== ''
                    ? $description
                    : null,
                $icon !== ''
                    ? $icon
                    : null,
                $featuredImageId,
                $bannerId,
                $status,
                $featured,
                $sortOrder
            ]);

            $_SESSION['services_success'] =
                'Service created successfully.';

            redirectServices();
        }


        /* =================================================
           DELETE
        ================================================= */

        if ($action === 'delete') {

            $id = filter_input(
                INPUT_POST,
                'id',
                FILTER_VALIDATE_INT
            );

            if (!$id || $id < 1) {
                throw new Exception(
                    'Invalid service selected.'
                );
            }


            /* ---------------------------------------------
               Check child services
            --------------------------------------------- */

            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM services
                WHERE parent_id = ?
            ");

            $stmt->execute([
                $id
            ]);

            $childCount =
                (int)$stmt->fetchColumn();


            if ($childCount > 0) {
                throw new Exception(
                    'This service has child services. Move or delete the child services first.'
                );
            }


            /* ---------------------------------------------
               DELETE
            --------------------------------------------- */

            $stmt = $pdo->prepare("
                DELETE FROM services
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $id
            ]);


            if ($stmt->rowCount() < 1) {
                throw new Exception(
                    'Service not found or already deleted.'
                );
            }


            $_SESSION['services_success'] =
                'Service deleted successfully.';

            redirectServices();
        }


        /* =================================================
           TOGGLE STATUS
        ================================================= */

        if ($action === 'toggle_status') {

            $id = filter_input(
                INPUT_POST,
                'id',
                FILTER_VALIDATE_INT
            );

            if (!$id || $id < 1) {
                throw new Exception(
                    'Invalid service selected.'
                );
            }


            $stmt = $pdo->prepare("
                SELECT status
                FROM services
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $id
            ]);

            $currentStatus =
                $stmt->fetchColumn();


            if ($currentStatus === false) {
                throw new Exception(
                    'Service not found.'
                );
            }


            $newStatus =
                ((int)$currentStatus === 1)
                ? 0
                : 1;


            $stmt = $pdo->prepare("
                UPDATE services
                SET status = ?
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $newStatus,
                $id
            ]);


            $_SESSION['services_success'] =
                $newStatus
                ? 'Service activated.'
                : 'Service deactivated.';

            redirectServices();
        }


        /* =================================================
           TOGGLE FEATURED
        ================================================= */

        if ($action === 'toggle_featured') {

            $id = filter_input(
                INPUT_POST,
                'id',
                FILTER_VALIDATE_INT
            );

            if (!$id || $id < 1) {
                throw new Exception(
                    'Invalid service selected.'
                );
            }


            $stmt = $pdo->prepare("
                SELECT featured
                FROM services
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $id
            ]);

            $currentFeatured =
                $stmt->fetchColumn();


            if ($currentFeatured === false) {
                throw new Exception(
                    'Service not found.'
                );
            }


            $newFeatured =
                ((int)$currentFeatured === 1)
                ? 0
                : 1;


            $stmt = $pdo->prepare("
                UPDATE services
                SET featured = ?
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $newFeatured,
                $id
            ]);


            $_SESSION['services_success'] =
                $newFeatured
                ? 'Service marked as featured.'
                : 'Service removed from featured.';

            redirectServices();
        }

    } catch (Throwable $ex) {

        $_SESSION['services_error'] =
            $ex->getMessage();

        redirectServices();
    }
}


/* =========================================================
   EDIT SERVICE
========================================================= */

$editId = filter_input(
    INPUT_GET,
    'edit',
    FILTER_VALIDATE_INT
);

$editData = null;

if ($editId && $editId > 0) {

    try {

        $stmt = $pdo->prepare("
            SELECT
                id,
                parent_id,
                name,
                slug,
                short_description,
                description,
                icon,
                featured_image_id,
                banner_id,
                status,
                featured,
                sort_order
            FROM services
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $editId
        ]);

        $editData =
            $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$editData) {
            $editId = null;
        }

    } catch (Throwable $ex) {
        $error =
            'Unable to load service for editing.';
    }
}


/* =========================================================
   FILTERS
========================================================= */

$search =
    trim($_GET['search'] ?? '');

$filterStatus =
    $_GET['status'] ?? '';

$filterFeatured =
    $_GET['featured'] ?? '';

$filterParent =
    filter_input(
        INPUT_GET,
        'parent_id',
        FILTER_VALIDATE_INT
    );

$filterParent =
    $filterParent ?: 0;


/* =========================================================
   BUILD WHERE
========================================================= */

$where = [];
$params = [];


if ($search !== '') {

    $where[] = "
        (
            s.name LIKE ?
            OR s.slug LIKE ?
            OR s.short_description LIKE ?
        )
    ";

    $like =
        '%' . $search . '%';

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}


if (
    $filterStatus === '1' ||
    $filterStatus === '0'
) {

    $where[] =
        's.status = ?';

    $params[] =
        (int)$filterStatus;
}


if (
    $filterFeatured === '1' ||
    $filterFeatured === '0'
) {

    $where[] =
        's.featured = ?';

    $params[] =
        (int)$filterFeatured;
}


if ($filterParent > 0) {

    $where[] =
        's.parent_id = ?';

    $params[] =
        $filterParent;
}


$whereSql = '';

if (!empty($where)) {

    $whereSql =
        'WHERE ' . implode(
            ' AND ',
            $where
        );
}


/* =========================================================
   PAGINATION
========================================================= */

$page =
    filter_input(
        INPUT_GET,
        'page',
        FILTER_VALIDATE_INT
    );

$page =
    $page && $page > 0
    ? $page
    : 1;

$perPage = 10;


/* =========================================================
   TOTAL
========================================================= */

$totalRows = 0;

try {

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM services s
        $whereSql
    ");

    $stmt->execute($params);

    $totalRows =
        (int)$stmt->fetchColumn();

} catch (Throwable $ex) {

    $error =
        'Unable to count services.';
}


$totalPages =
    max(
        1,
        (int)ceil(
            $totalRows / $perPage
        )
    );


if ($page > $totalPages) {
    $page = $totalPages;
}


$offset =
    ($page - 1) * $perPage;


/* =========================================================
   GET SERVICES
========================================================= */

$services = [];

try {

    $sql = "
        SELECT
            s.id,
            s.parent_id,
            s.name,
            s.slug,
            s.short_description,
            s.description,
            s.icon,
            s.featured_image_id,
            s.banner_id,
            s.status,
            s.featured,
            s.sort_order,
            s.created_at,
            s.updated_at,

            p.name AS parent_name

        FROM services s

        LEFT JOIN services p
            ON p.id = s.parent_id

        $whereSql

        ORDER BY
            s.sort_order ASC,
            s.id DESC

        LIMIT $perPage
        OFFSET $offset
    ";

    $stmt =
        $pdo->prepare($sql);

    $stmt->execute($params);

    $services =
        $stmt->fetchAll(
            PDO::FETCH_ASSOC
        );

} catch (Throwable $ex) {

    $error =
        'Unable to load services.';
}


/* =========================================================
   ALL PARENTS
========================================================= */

$parentServices = [];

try {

    $stmt = $pdo->query("
        SELECT
            id,
            parent_id,
            name,
            slug,
            status
        FROM services
        ORDER BY
            sort_order ASC,
            name ASC
    ");

    $parentServices =
        $stmt->fetchAll(
            PDO::FETCH_ASSOC
        );

} catch (Throwable $ex) {

    $parentServices = [];
}


/* =========================================================
   STATISTICS
========================================================= */

$totalServices = 0;
$activeServices = 0;
$featuredServices = 0;
$parentServicesCount = 0;

try {

    $totalServices =
        (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM services
        ")
        ->fetchColumn();


    $activeServices =
        (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM services
            WHERE status = 1
        ")
        ->fetchColumn();


    $featuredServices =
        (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM services
            WHERE featured = 1
        ")
        ->fetchColumn();


    $parentServicesCount =
        (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM services
            WHERE parent_id IS NULL
        ")
        ->fetchColumn();

} catch (Throwable $ex) {
    /* Stats optional */
}


/* =========================================================
   ADMIN
========================================================= */

$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? 'Administrator';


$adminInitial =
    strtoupper(
        substr(
            trim($adminName),
            0,
            1
        )
    );


if ($adminInitial === '') {
    $adminInitial = 'A';
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Services | Pure Chemical Admin
    </title>

    <meta
        name="robots"
        content="noindex,nofollow"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --bg: #f5f7fb;
            --card: #ffffff;

            --border: #e7eaf0;

            --text: #111827;
            --muted: #6b7280;

            --success: #059669;
            --success-bg: #ecfdf5;

            --danger: #dc2626;
            --danger-bg: #fef2f2;

            --warning: #d97706;
            --warning-bg: #fffbeb;

            --blue: #2563eb;
            --blue-bg: #eff6ff;

            --purple: #7c3aed;
            --purple-bg: #f5f3ff;

            --shadow:
                0 16px 45px rgba(15, 23, 42, .07);

            --radius: 18px;
        }


        * {
            box-sizing: border-box;
        }


        body {
            margin: 0;

            background: var(--bg);

            color: var(--text);

            font-family: "Inter", sans-serif;

            font-size: 14px;
        }


        a {
            text-decoration: none;
            color: inherit;
        }


        button,
        input,
        select,
        textarea {
            font-family: inherit;
        }


        /* =================================================
           PAGE
        ================================================= */

        .pc-page {
            margin-left: 280px;
            min-height: 100vh;
        }


        .pc-container {
            width: min(
                1550px,
                calc(100% - 48px)
            );

            margin: auto;

            padding: 25px 0 55px;
        }


        /* =================================================
           TOPBAR
        ================================================= */

        .pc-topbar {
            position: sticky;
            top: 0;
            z-index: 100;

            height: 76px;

            padding: 0 28px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            background:
                rgba(255,255,255,.94);

            border-bottom:
                1px solid var(--border);

            backdrop-filter:
                blur(18px);
        }


        .pc-top-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }


        .pc-mobile-btn {
            display: none;

            width: 42px;
            height: 42px;

            border: 1px solid var(--border);

            border-radius: 12px;

            background: #fff;

            cursor: pointer;
        }


        .pc-title {
            margin: 0;

            font-size: 19px;

            font-weight: 800;

            letter-spacing: -.4px;
        }


        .pc-breadcrumb {
            margin-top: 4px;

            color: var(--muted);

            font-size: 11px;
        }


        .pc-top-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }


        .pc-dashboard {
            height: 40px;

            display: inline-flex;
            align-items: center;
            gap: 8px;

            padding: 0 13px;

            border: 1px solid var(--border);

            border-radius: 11px;

            background: #fff;

            font-size: 12px;
            font-weight: 700;
        }


        .pc-admin {
            display: flex;
            align-items: center;
            gap: 9px;
        }


        .pc-avatar {
            width: 40px;
            height: 40px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #14b8a6
                );

            color: #fff;

            font-weight: 800;
        }


        .pc-admin-name {
            font-size: 12px;
            font-weight: 800;
        }


        .pc-admin-role {
            margin-top: 2px;

            color: var(--muted);

            font-size: 10px;
        }


        /* =================================================
           HERO
        ================================================= */

        .pc-hero {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;

            gap: 20px;

            margin-bottom: 22px;
        }


        .pc-eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            padding: 7px 11px;

            border-radius: 999px;

            background: var(--primary-soft);

            color: var(--primary-dark);

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .7px;
        }


        .pc-hero h1 {
            margin: 12px 0 6px;

            font-size: 29px;

            line-height: 1.15;

            letter-spacing: -.8px;
        }


        .pc-hero p {
            margin: 0;

            max-width: 760px;

            color: var(--muted);

            line-height: 1.6;
        }


        /* =================================================
           STATS
        ================================================= */

        .pc-stats {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 20px;
        }


        .pc-stat {
            position: relative;

            overflow: hidden;

            padding: 19px;

            background: var(--card);

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }


        .pc-stat-icon {
            width: 42px;
            height: 42px;

            display: grid;
            place-items: center;

            border-radius: 12px;

            background: var(--primary-soft);

            color: var(--primary);

            margin-bottom: 13px;
        }


        .pc-stat:nth-child(2)
        .pc-stat-icon {
            background: var(--blue-bg);
            color: var(--blue);
        }


        .pc-stat:nth-child(3)
        .pc-stat-icon {
            background: var(--purple-bg);
            color: var(--purple);
        }


        .pc-stat:nth-child(4)
        .pc-stat-icon {
            background: var(--warning-bg);
            color: var(--warning);
        }


        .pc-stat-value {
            font-size: 26px;

            font-weight: 800;

            letter-spacing: -.6px;
        }


        .pc-stat-label {
            margin-top: 4px;

            color: var(--muted);

            font-size: 11px;

            font-weight: 600;
        }


        /* =================================================
           ALERT
        ================================================= */

        .pc-alert {
            display: flex;

            align-items: flex-start;

            gap: 10px;

            padding: 14px 16px;

            margin-bottom: 18px;

            border-radius: 13px;

            font-size: 12px;

            line-height: 1.5;
        }


        .pc-alert.success {
            color: #065f46;

            background: var(--success-bg);

            border: 1px solid #a7f3d0;
        }


        .pc-alert.error {
            color: #991b1b;

            background: var(--danger-bg);

            border: 1px solid #fecaca;
        }


        /* =================================================
           MAIN CARD
        ================================================= */

        .pc-card {
            background: var(--card);

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow);

            overflow: hidden;
        }


        .pc-card-header {
            padding: 19px 21px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            border-bottom:
                1px solid var(--border);
        }


        .pc-card-title {
            margin: 0;

            font-size: 15px;

            font-weight: 800;
        }


        .pc-card-subtitle {
            margin: 4px 0 0;

            color: var(--muted);

            font-size: 11px;

            line-height: 1.5;
        }


        /* =================================================
           FILTERS
        ================================================= */

        .pc-filter {
            padding: 15px 18px;

            background: #fbfcfe;

            border-bottom:
                1px solid var(--border);
        }


        .pc-filter-form {
            display: grid;

            grid-template-columns:
                minmax(220px, 1fr)
                180px
                180px
                180px
                auto;

            gap: 9px;
        }


        .pc-input,
        .pc-select,
        .pc-textarea {
            width: 100%;

            border: 1px solid #dfe3ea;

            border-radius: 11px;

            background: #fff;

            color: var(--text);

            outline: none;

            font-size: 12px;

            transition: .2s ease;
        }


        .pc-input,
        .pc-select {
            height: 44px;

            padding: 0 12px;
        }


        .pc-textarea {
            min-height: 125px;

            padding: 12px;

            resize: vertical;

            line-height: 1.6;
        }


        .pc-input:focus,
        .pc-select:focus,
        .pc-textarea:focus {
            border-color: var(--primary);

            box-shadow:
                0 0 0 4px
                rgba(15,118,110,.08);
        }


        .pc-search {
            position: relative;
        }


        .pc-search i {
            position: absolute;

            left: 13px;
            top: 50%;

            transform:
                translateY(-50%);

            color: #9ca3af;
        }


        .pc-search .pc-input {
            padding-left: 38px;
        }


        /* =================================================
           BUTTONS
        ================================================= */

        .pc-btn {
            min-height: 43px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 7px;

            padding: 0 14px;

            border-radius: 10px;

            border: 1px solid transparent;

            cursor: pointer;

            font-size: 11px;

            font-weight: 800;

            transition: .2s ease;
        }


        .pc-btn:hover {
            transform: translateY(-1px);
        }


        .pc-btn-primary {
            color: #fff;

            background: var(--primary);

            box-shadow:
                0 8px 18px
                rgba(15,118,110,.16);
        }


        .pc-btn-primary:hover {
            background: var(--primary-dark);
        }


        .pc-btn-light {
            color: #374151;

            background: #fff;

            border-color: var(--border);
        }


        .pc-btn-danger {
            color: var(--danger);

            background: var(--danger-bg);

            border-color: #fecaca;
        }


        /* =================================================
           TABLE
        ================================================= */

        .pc-table-wrap {
            overflow-x: auto;
        }


        .pc-table {
            width: 100%;

            border-collapse: collapse;
        }


        .pc-table th {
            padding: 13px 17px;

            text-align: left;

            background: #fafbfc;

            border-bottom:
                1px solid var(--border);

            color: #6b7280;

            font-size: 9px;

            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .7px;

            white-space: nowrap;
        }


        .pc-table td {
            padding: 15px 17px;

            border-bottom:
                1px solid #eef0f4;

            vertical-align: middle;
        }


        .pc-table tbody tr {
            transition: .15s ease;
        }


        .pc-table tbody tr:hover {
            background: #fcfefe;
        }


        /* =================================================
           SERVICE
        ================================================= */

        .pc-service {
            display: flex;

            align-items: center;

            gap: 11px;

            min-width: 230px;
        }


        .pc-service-icon {
            width: 40px;
            height: 40px;

            flex: 0 0 40px;

            display: grid;

            place-items: center;

            border-radius: 11px;

            background: var(--primary-soft);

            color: var(--primary);

            overflow: hidden;
        }


        .pc-service-icon img {
            width: 100%;
            height: 100%;

            object-fit: cover;
        }


        .pc-service-name {
            font-size: 12px;

            font-weight: 800;
        }


        .pc-service-slug {
            margin-top: 3px;

            color: var(--muted);

            font-size: 9px;
        }


        .pc-parent {
            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding: 7px 9px;

            border-radius: 8px;

            background: #f8fafc;

            border: 1px solid #edf0f4;

            color: #4b5563;

            font-size: 10px;

            font-weight: 700;
        }


        .pc-root {
            color: var(--primary);

            background: var(--primary-soft);

            border-color: #d1fae5;
        }


        /* =================================================
           BADGES
        ================================================= */

        .pc-badge {
            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding: 6px 9px;

            border-radius: 999px;

            font-size: 9px;

            font-weight: 800;
        }


        .pc-active {
            color: #047857;

            background: #ecfdf5;
        }


        .pc-inactive {
            color: #b91c1c;

            background: #fef2f2;
        }


        .pc-featured {
            color: #92400e;

            background: #fffbeb;
        }


        .pc-normal {
            color: #6b7280;

            background: #f3f4f6;
        }


        .pc-order {
            min-width: 31px;

            height: 29px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            padding: 0 7px;

            border-radius: 8px;

            background: #f3f4f6;

            font-size: 10px;

            font-weight: 800;
        }


        /* =================================================
           ACTIONS
        ================================================= */

        .pc-actions {
            display: flex;

            justify-content: flex-end;

            gap: 6px;
        }


        .pc-icon-btn {
            width: 34px;
            height: 34px;

            display: inline-grid;

            place-items: center;

            border-radius: 9px;

            border: 1px solid var(--border);

            background: #fff;

            color: #4b5563;

            cursor: pointer;

            transition: .2s ease;
        }


        .pc-icon-btn:hover {
            transform: translateY(-1px);

            border-color: #cbd5e1;
        }


        .pc-icon-btn.green {
            color: var(--success);

            background: var(--success-bg);

            border-color: #a7f3d0;
        }


        .pc-icon-btn.orange {
            color: var(--warning);

            background: var(--warning-bg);

            border-color: #fde68a;
        }


        .pc-icon-btn.red {
            color: var(--danger);

            background: var(--danger-bg);

            border-color: #fecaca;
        }


        /* =================================================
           PAGINATION
        ================================================= */

        .pc-pagination {
            padding: 15px 17px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;
        }


        .pc-page-info {
            color: var(--muted);

            font-size: 10px;

            font-weight: 600;
        }


        .pc-pages {
            display: flex;

            align-items: center;

            gap: 5px;
        }


        .pc-page-btn {
            min-width: 33px;

            height: 33px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            padding: 0 8px;

            border:
                1px solid var(--border);

            border-radius: 8px;

            background: #fff;

            color: #4b5563;

            font-size: 10px;

            font-weight: 800;
        }


        .pc-page-btn.active {
            color: #fff;

            background: var(--primary);

            border-color: var(--primary);
        }


        .pc-page-btn.disabled {
            opacity: .4;

            pointer-events: none;
        }


        /* =================================================
           EMPTY
        ================================================= */

        .pc-empty {
            padding: 65px 20px;

            text-align: center;
        }


        .pc-empty-icon {
            width: 58px;
            height: 58px;

            display: grid;

            place-items: center;

            margin:
                0 auto 14px;

            border-radius: 17px;

            background: var(--primary-soft);

            color: var(--primary);

            font-size: 21px;
        }


        .pc-empty h3 {
            margin: 0 0 6px;

            font-size: 15px;
        }


        .pc-empty p {
            margin: 0;

            color: var(--muted);

            font-size: 11px;
        }


        /* =================================================
           MODAL (Fixed Z-Index so it never cuts behind sidebar)
        ================================================= */

        .pc-modal {
            position: fixed;

            inset: 0;

            z-index: 9999;

            display: none;

            align-items: center;

            justify-content: center;

            padding: 20px;

            background:
                rgba(15,23,42,.58);

            backdrop-filter:
                blur(7px);
        }


        .pc-modal.show {
            display: flex;
        }


        .pc-modal-box {
            width: min(
                850px,
                100%
            );

            max-height: 92vh;

            overflow-y: auto;

            background: #fff;

            border-radius: 20px;

            box-shadow:
                0 30px 90px
                rgba(0,0,0,.22);
        }


        .pc-modal-header {
            padding: 19px 22px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            border-bottom:
                1px solid var(--border);
        }


        .pc-modal-title {
            margin: 0;

            font-size: 16px;

            font-weight: 800;
        }


        .pc-modal-close {
            width: 35px;
            height: 35px;

            border: 0;

            border-radius: 9px;

            background: #f3f4f6;

            cursor: pointer;
        }


        .pc-modal-body {
            padding: 22px;
        }


        .pc-form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }


        .pc-form-full {
            grid-column:
                1 / -1;
        }


        .pc-label {
            display: block;

            margin-bottom: 7px;

            color: #374151;

            font-size: 11px;

            font-weight: 800;
        }


        .pc-required {
            color: var(--danger);
        }


        .pc-help {
            margin-top: 6px;

            color: var(--muted);

            font-size: 9px;

            line-height: 1.5;
        }


        .pc-check-row {
            display: flex;

            align-items: center;

            gap: 20px;

            padding: 12px 0;
        }


        .pc-check {
            display: inline-flex;

            align-items: center;

            gap: 8px;

            cursor: pointer;

            font-size: 11px;

            font-weight: 700;
        }


        .pc-check input {
            width: 16px;
            height: 16px;

            accent-color: var(--primary);
        }


        .pc-modal-actions {
            display: flex;

            justify-content: flex-end;

            gap: 8px;

            margin-top: 22px;

            padding-top: 18px;

            border-top:
                1px solid var(--border);
        }


        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1250px) {

            .pc-filter-form {
                grid-template-columns:
                    1fr 1fr 1fr;
            }

            .pc-filter-form
            .pc-search {
                grid-column:
                    1 / -1;
            }

        }


        @media (max-width: 1100px) {

            .pc-page {
                margin-left: 0;
            }

            .pc-mobile-btn {
                display: grid;
                place-items: center;
            }

            .pc-stats {
                grid-template-columns:
                    repeat(2, 1fr);
            }

        }


        @media (max-width: 750px) {

            .pc-topbar {
                height: 68px;
                padding: 0 15px;
            }

            .pc-admin-name,
            .pc-admin-role {
                display: none;
            }

            .pc-dashboard span {
                display: none;
            }

            .pc-container {
                width:
                    calc(100% - 24px);

                padding-top: 18px;
            }

            .pc-hero h1 {
                font-size: 24px;
            }

            .pc-stats {
                grid-template-columns: 1fr;
            }

            .pc-filter-form {
                grid-template-columns: 1fr;
            }

            .pc-filter-form
            .pc-search {
                grid-column: auto;
            }

            .pc-form-grid {
                grid-template-columns: 1fr;
            }

            .pc-form-full {
                grid-column: auto;
            }

            .pc-pagination {
                flex-direction: column;

                align-items: flex-start;
            }

        }


        @media (max-width: 500px) {

            .pc-top-right {
                gap: 5px;
            }

            .pc-avatar {
                width: 36px;
                height: 36px;
            }

            .pc-title {
                font-size: 15px;
            }

            .pc-breadcrumb {
                display: none;
            }

            .pc-card-header {
                align-items: flex-start;

                flex-direction: column;
            }

            .pc-modal {
                padding: 10px;
            }

            .pc-modal-body {
                padding: 17px;
            }

        }

    </style>

</head>


<body>


<?php
/*
|--------------------------------------------------------------------------
| SEPARATE SIDEBAR
|--------------------------------------------------------------------------
|
| User requested:
| admin/sidebar.php separately include.
|
| header.php intentionally NOT included.
|
*/
require_once __DIR__ . '/sidebar.php';
?>


<div class="pc-page">


    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div class="pc-top-left">

            <button
                type="button"
                class="pc-mobile-btn"
                onclick="toggleSidebar()"
                aria-label="Toggle sidebar"
            >
                <i class="fa-solid fa-bars"></i>
            </button>


            <div>

                <h2 class="pc-title">
                    Services
                </h2>

                <div class="pc-breadcrumb">
                    Admin / Services
                </div>

            </div>

        </div>


        <div class="pc-top-right">

            <a
                href="index.php"
                class="pc-dashboard"
            >
                <i class="fa-solid fa-gauge-high"></i>
                <span>Dashboard</span>
            </a>


            <div class="pc-admin">

                <div class="pc-avatar">
                    <?= e($adminInitial) ?>
                </div>

                <div>

                    <div class="pc-admin-name">
                        <?= e($adminName) ?>
                    </div>

                    <div class="pc-admin-role">
                        Administrator
                    </div>

                </div>

            </div>

        </div>

    </header>


    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="pc-container">


        <!-- HERO -->

        <section class="pc-hero">

            <div>

                <span class="pc-eyebrow">

                    <i class="fa-solid fa-briefcase"></i>

                    Content Management

                </span>


                <h1>
                    Services
                </h1>


                <p>
                    Website ke services section ko manage karein.
                    Parent-child services, descriptions, images,
                    status, featured services aur display order
                    ek hi jagah se control karein.
                </p>

            </div>


            <div>

                <button
                    type="button"
                    class="pc-btn pc-btn-primary"
                    onclick="openServiceModal()"
                >

                    <i class="fa-solid fa-plus"></i>

                    Add Service

                </button>

            </div>

        </section>


        <!-- =================================================
             FLASH
        ================================================== -->

        <?php if ($success): ?>

            <div class="pc-alert success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?= e($success) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if ($error): ?>

            <div class="pc-alert error">

                <i class="fa-solid fa-triangle-exclamation"></i>

                <div>
                    <?= e($error) ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="pc-stats">


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-briefcase"></i>

                </div>

                <div class="pc-stat-value">
                    <?= number_format($totalServices) ?>
                </div>

                <div class="pc-stat-label">
                    Total Services
                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-circle-check"></i>

                </div>

                <div class="pc-stat-value">
                    <?= number_format($activeServices) ?>
                </div>

                <div class="pc-stat-label">
                    Active Services
                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-star"></i>

                </div>

                <div class="pc-stat-value">
                    <?= number_format($featuredServices) ?>
                </div>

                <div class="pc-stat-label">
                    Featured Services
                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">

                    <i class="fa-solid fa-layer-group"></i>

                </div>

                <div class="pc-stat-value">
                    <?= number_format($parentServicesCount) ?>
                </div>

                <div class="pc-stat-label">
                    Main Services
                </div>

            </div>


        </section>


        <!-- =================================================
             SERVICE LIST
        ================================================== -->

        <section class="pc-card">


            <div class="pc-card-header">

                <div>

                    <h3 class="pc-card-title">
                        All Services
                    </h3>

                    <p class="pc-card-subtitle">
                        Manage your website services and hierarchy.
                    </p>

                </div>


                <span class="pc-eyebrow">
                    <?= number_format($totalRows) ?>
                    Records
                </span>

            </div>


            <!-- FILTER -->

            <div class="pc-filter">

                <form
                    method="GET"
                    class="pc-filter-form"
                >


                    <div class="pc-search">

                        <i class="fa-solid fa-magnifying-glass"></i>

                        <input
                            type="search"
                            name="search"
                            class="pc-input"
                            value="<?= e($search) ?>"
                            placeholder="Search service name, slug or description..."
                        >

                    </div>


                    <select
                        name="status"
                        class="pc-select"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="1"
                            <?= $filterStatus === '1'
                                ? 'selected'
                                : '' ?>
                        >
                            Active
                        </option>

                        <option
                            value="0"
                            <?= $filterStatus === '0'
                                ? 'selected'
                                : '' ?>
                        >
                            Inactive
                        </option>

                    </select>


                    <select
                        name="featured"
                        class="pc-select"
                    >

                        <option value="">
                            All Featured
                        </option>

                        <option
                            value="1"
                            <?= $filterFeatured === '1'
                                ? 'selected'
                                : '' ?>
                        >
                            Featured
                        </option>

                        <option
                            value="0"
                            <?= $filterFeatured === '0'
                                ? 'selected'
                                : '' ?>
                        >
                            Normal
                        </option>

                    </select>


                    <select
                        name="parent_id"
                        class="pc-select"
                    >

                        <option value="">
                            All Parent Levels
                        </option>

                        <option
                            value="-1"
                            <?= isset($_GET['parent_id'])
                                && $_GET['parent_id'] === '-1'
                                ? 'selected'
                                : '' ?>
                        >
                            Main Services
                        </option>

                        <?php foreach ($parentServices as $parent): ?>

                            <?php if ((int)$parent['parent_id'] === 0 || $parent['parent_id'] === null): ?>

                                <option
                                    value="<?= (int)$parent['id'] ?>"
                                    <?= $filterParent === (int)$parent['id']
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= e($parent['name']) ?>
                                </option>

                            <?php endif; ?>

                        <?php endforeach; ?>

                    </select>


                    <button
                        type="submit"
                        class="pc-btn pc-btn-primary"
                    >

                        <i class="fa-solid fa-filter"></i>

                        Filter

                    </button>


                </form>

            </div>


            <!-- TABLE -->

            <?php if (!empty($services)): ?>

                <div class="pc-table-wrap">

                    <table class="pc-table">

                        <thead>

                            <tr>

                                <th>
                                    Service
                                </th>

                                <th>
                                    Parent
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Featured
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Media
                                </th>

                                <th style="text-align:right;">
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>

                        <?php foreach ($services as $service): ?>

                            <?php

                            $serviceIcon =
                                trim(
                                    (string)(
                                        $service['icon']
                                        ?? ''
                                    )
                                );

                            ?>


                            <tr>


                                <!-- SERVICE -->

                                <td>

                                    <div class="pc-service">


                                        <div class="pc-service-icon">

                                            <?php if ($serviceIcon !== ''): ?>

                                                <?php if (
                                                    preg_match(
                                                        '/\.(jpg|jpeg|png|gif|webp|svg)$/i',
                                                        $serviceIcon
                                                    )
                                                ): ?>

                                                    <img
                                                        src="<?= e($serviceIcon) ?>"
                                                        alt="<?= e($service['name']) ?>"
                                                    >

                                                <?php else: ?>

                                                    <i class="<?= e($serviceIcon) ?>"></i>

                                                <?php endif; ?>

                                            <?php else: ?>

                                                <i class="fa-solid fa-briefcase"></i>

                                            <?php endif; ?>

                                        </div>


                                        <div>

                                            <div class="pc-service-name">
                                                <?= e($service['name']) ?>
                                            </div>

                                            <div class="pc-service-slug">

                                                /<?= e($service['slug']) ?>

                                                · ID
                                                <?= (int)$service['id'] ?>

                                            </div>

                                        </div>


                                    </div>

                                </td>


                                <!-- PARENT -->

                                <td>

                                    <?php if (!empty($service['parent_name'])): ?>

                                        <span class="pc-parent">

                                            <i class="fa-solid fa-turn-up"></i>

                                            <?= e($service['parent_name']) ?>

                                        </span>

                                    <?php else: ?>

                                        <span class="pc-parent pc-root">

                                            <i class="fa-solid fa-layer-group"></i>

                                            Main Service

                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <form
                                        method="POST"
                                        style="display:inline;"
                                    >

                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?= e($csrfToken) ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_status"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= (int)$service['id'] ?>"
                                        >


                                        <button
                                            type="submit"
                                            class="pc-badge <?= (int)$service['status'] === 1
                                                ? 'pc-active'
                                                : 'pc-inactive' ?>"
                                            title="Toggle status"
                                            style="border:0;cursor:pointer;"
                                        >

                                            <i class="fa-solid
                                                <?= (int)$service['status'] === 1
                                                    ? 'fa-circle-check'
                                                    : 'fa-circle-xmark' ?>">
                                            </i>

                                            <?= (int)$service['status'] === 1
                                                ? 'Active'
                                                : 'Inactive' ?>

                                        </button>

                                    </form>

                                </td>


                                <!-- FEATURED -->

                                <td>

                                    <form
                                        method="POST"
                                        style="display:inline;"
                                    >

                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?= e($csrfToken) ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_featured"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= (int)$service['id'] ?>"
                                        >


                                        <button
                                            type="submit"
                                            class="pc-badge <?= (int)$service['featured'] === 1
                                                ? 'pc-featured'
                                                : 'pc-normal' ?>"
                                            title="Toggle featured"
                                            style="border:0;cursor:pointer;"
                                        >

                                            <i class="fa-solid fa-star"></i>

                                            <?= (int)$service['featured'] === 1
                                                ? 'Featured'
                                                : 'Normal' ?>

                                        </button>

                                    </form>

                                </td>


                                <!-- SORT -->

                                <td>

                                    <span class="pc-order">

                                        <?= (int)$service['sort_order'] ?>

                                    </span>

                                </td>


                                <!-- MEDIA -->

                                <td>

                                    <div
                                        style="
                                            display:flex;
                                            gap:5px;
                                            flex-wrap:wrap;
                                        "
                                    >

                                        <?php if (
                                            !empty(
                                                $service['featured_image_id']
                                            )
                                        ): ?>

                                            <span
                                                class="pc-badge"
                                                style="
                                                    color:#2563eb;
                                                    background:#eff6ff;
                                                "
                                                title="Featured Image ID"
                                            >
                                                <i class="fa-solid fa-image"></i>
                                                <?= (int)$service['featured_image_id'] ?>
                                            </span>

                                        <?php endif; ?>


                                        <?php if (
                                            !empty(
                                                $service['banner_id']
                                            )
                                        ): ?>

                                            <span
                                                class="pc-badge"
                                                style="
                                                    color:#7c3aed;
                                                    background:#f5f3ff;
                                                "
                                                title="Banner ID"
                                            >
                                                <i class="fa-solid fa-panorama"></i>
                                                <?= (int)$service['banner_id'] ?>
                                            </span>

                                        <?php endif; ?>


                                        <?php if (
                                            empty(
                                                $service['featured_image_id']
                                            )
                                            &&
                                            empty(
                                                $service['banner_id']
                                            )
                                        ): ?>

                                            <span
                                                style="
                                                    color:#9ca3af;
                                                    font-size:10px;
                                                "
                                            >
                                                No media
                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="pc-actions">


                                        <!-- EDIT -->

                                        <a
                                            href="?edit=<?= (int)$service['id'] ?>"
                                            class="pc-icon-btn"
                                            title="Edit Service"
                                        >

                                            <i class="fa-solid fa-pen"></i>

                                        </a>


                                        <!-- DELETE -->

                                        <form
                                            method="POST"
                                            onsubmit="return confirmServiceDelete(
                                                '<?= e($service['name']) ?>'
                                            );"
                                            style="display:inline;"
                                        >

                                            <input
                                                type="hidden"
                                                name="csrf_token"
                                                value="<?= e($csrfToken) ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$service['id'] ?>"
                                            >


                                            <button
                                                type="submit"
                                                class="pc-icon-btn red"
                                                title="Delete Service"
                                            >

                                                <i class="fa-solid fa-trash"></i>

                                            </button>

                                        </form>


                                    </div>

                                </td>


                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>


                <!-- =================================================
                     PAGINATION
                ================================================== -->

                <?php if ($totalPages > 1): ?>

                    <div class="pc-pagination">


                        <div class="pc-page-info">

                            Showing

                            <strong>
                                <?= $totalRows > 0
                                    ? $offset + 1
                                    : 0 ?>
                            </strong>

                            –

                            <strong>
                                <?= min(
                                    $offset + $perPage,
                                    $totalRows
                                ) ?>
                            </strong>

                            of

                            <strong>
                                <?= number_format($totalRows) ?>
                            </strong>

                        </div>


                        <div class="pc-pages">


                            <?php

                            $prevUrl =
                                '?' . http_build_query([
                                    'search' =>
                                        $search,

                                    'status' =>
                                        $filterStatus,

                                    'featured' =>
                                        $filterFeatured,

                                    'parent_id' =>
                                        $_GET['parent_id'] ?? '',

                                    'page' =>
                                        max(
                                            1,
                                            $page - 1
                                        )
                                ]);

                            ?>


                            <a
                                href="<?= e($prevUrl) ?>"
                                class="pc-page-btn <?= $page <= 1
                                    ? 'disabled'
                                    : '' ?>"
                            >

                                <i class="fa-solid fa-chevron-left"></i>

                            </a>


                            <?php

                            $startPage =
                                max(
                                    1,
                                    $page - 2
                                );

                            $endPage =
                                min(
                                    $totalPages,
                                    $page + 2
                                );

                            for (
                                $p = $startPage;
                                $p <= $endPage;
                                $p++
                            ):

                                $pageUrl =
                                    '?' . http_build_query([
                                        'search' =>
                                            $search,

                                        'status' =>
                                            $filterStatus,

                                        'featured' =>
                                            $filterFeatured,

                                        'parent_id' =>
                                            $_GET['parent_id'] ?? '',

                                        'page' =>
                                            $p
                                    ]);

                            ?>

                                <a
                                    href="<?= e($pageUrl) ?>"
                                    class="pc-page-btn <?= $p === $page
                                        ? 'active'
                                        : '' ?>"
                                >
                                    <?= $p ?>
                                </a>

                            <?php endfor; ?>


                            <?php

                            $nextUrl =
                                '?' . http_build_query([
                                    'search' =>
                                        $search,

                                    'status' =>
                                        $filterStatus,

                                    'featured' =>
                                        $filterFeatured,

                                    'parent_id' =>
                                        $_GET['parent_id'] ?? '',

                                    'page' =>
                                        min(
                                            $totalPages,
                                            $page + 1
                                        )
                                ]);

                            ?>


                            <a
                                href="<?= e($nextUrl) ?>"
                                class="pc-page-btn <?= $page >= $totalPages
                                    ? 'disabled'
                                    : '' ?>"
                            >

                                <i class="fa-solid fa-chevron-right"></i>

                            </a>


                        </div>


                    </div>

                <?php endif; ?>


            <?php else: ?>


                <div class="pc-empty">

                    <div class="pc-empty-icon">

                        <i class="fa-solid fa-briefcase"></i>

                    </div>


                    <h3>
                        No Services Found
                    </h3>


                    <p>
                        Abhi services available nahi hain.
                        Add Service button se pehli service create karein.
                    </p>

                </div>


            <?php endif; ?>


        </section>


    </main>

</div>


<!-- =========================================================
     ADD / EDIT MODAL
========================================================= -->

<div
    class="pc-modal <?= $editData ? 'show' : '' ?>"
    id="serviceModal"
>


    <div class="pc-modal-box">


        <div class="pc-modal-header">

            <div>

                <h3 class="pc-modal-title">

                    <?= $editData
                        ? 'Edit Service'
                        : 'Create New Service' ?>

                </h3>

            </div>


            <button
                type="button"
                class="pc-modal-close"
                onclick="closeServiceModal()"
            >

                <i class="fa-solid fa-xmark"></i>

            </button>

        </div>


        <div class="pc-modal-body">


            <form
                method="POST"
                action="<?= e(basename($_SERVER['PHP_SELF'])) ?>"
            >


                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= e($csrfToken) ?>"
                >


                <input
                    type="hidden"
                    name="action"
                    value="save"
                >


                <?php if ($editData): ?>

                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)$editData['id'] ?>"
                    >

                <?php endif; ?>


                <div class="pc-form-grid">


                    <!-- NAME -->

                    <div class="pc-form-full">

                        <label
                            class="pc-label"
                            for="service_name"
                        >

                            Service Name

                            <span class="pc-required">
                                *
                            </span>

                        </label>


                        <input
                            type="text"
                            id="service_name"
                            name="name"
                            class="pc-input"
                            maxlength="255"
                            required
                            value="<?= e(
                                $editData['name']
                                ?? ''
                            ) ?>"
                            placeholder="Enter service name"
                        >


                        <div class="pc-help">
                            Example: Chemical Consulting,
                            Laboratory Services, Bulk Chemical Supply etc.
                        </div>

                    </div>


                    <!-- SLUG -->

                    <div>

                        <label
                            class="pc-label"
                            for="service_slug"
                        >
                            Slug
                            <span class="pc-required">*</span>
                        </label>


                        <input
                            type="text"
                            id="service_slug"
                            name="slug"
                            class="pc-input"
                            maxlength="255"
                            value="<?= e(
                                $editData['slug']
                                ?? ''
                            ) ?>"
                            placeholder="service-slug"
                        >


                        <div class="pc-help">
                            Empty chhodne par name se automatically generate hoga.
                        </div>

                    </div>


                    <!-- PARENT -->

                    <div>

                        <label
                            class="pc-label"
                            for="parent_id"
                        >
                            Parent Service
                        </label>


                        <select
                            name="parent_id"
                            id="parent_id"
                            class="pc-select"
                        >

                            <option value="">
                                No Parent — Main Service
                            </option>


                            <?php foreach (
                                $parentServices
                                as $parent
                            ): ?>


                                <?php

                                if (
                                    $editData
                                    &&
                                    (int)$parent['id']
                                    === (int)$editData['id']
                                ) {
                                    continue;
                                }

                                ?>


                                <option
                                    value="<?= (int)$parent['id'] ?>"
                                    <?= (
                                        (int)(
                                            $editData['parent_id']
                                            ?? 0
                                        )
                                        ===
                                        (int)$parent['id']
                                    )
                                        ? 'selected'
                                        : '' ?>
                                >

                                    <?= e(
                                        $parent['name']
                                    ) ?>

                                    —
                                    #<?= (int)$parent['id'] ?>

                                </option>


                            <?php endforeach; ?>


                        </select>


                        <div class="pc-help">
                            Parent select karke nested/sub-service hierarchy bana sakte hain.
                        </div>

                    </div>


                    <!-- SHORT DESCRIPTION -->

                    <div class="pc-form-full">

                        <label
                            class="pc-label"
                            for="short_description"
                        >
                            Short Description
                        </label>


                        <textarea
                            id="short_description"
                            name="short_description"
                            class="pc-textarea"
                            rows="4"
                            placeholder="Short service description..."
                        ><?= e(
                            $editData['short_description']
                            ?? ''
                        ) ?></textarea>

                    </div>


                    <!-- DESCRIPTION -->

                    <div class="pc-form-full">

                        <label
                            class="pc-label"
                            for="description"
                        >
                            Full Description
                        </label>


                        <textarea
                            id="description"
                            name="description"
                            class="pc-textarea"
                            rows="7"
                            placeholder="Complete service description..."
                        ><?= e(
                            $editData['description']
                            ?? ''
                        ) ?></textarea>


                        <div class="pc-help">
                            Full service detail content yahan enter karein.
                        </div>

                    </div>


                    <!-- ICON -->

                    <div>

                        <label
                            class="pc-label"
                            for="icon"
                        >
                            Icon
                        </label>


                        <input
                            type="text"
                            id="icon"
                            name="icon"
                            class="pc-input"
                            maxlength="150"
                            value="<?= e(
                                $editData['icon']
                                ?? ''
                            ) ?>"
                            placeholder="fa-solid fa-flask"
                        >


                        <div class="pc-help">
                            Font Awesome class ya icon/image path store kar sakte hain.
                        </div>

                    </div>


                    <!-- SORT -->

                    <div>

                        <label
                            class="pc-label"
                            for="sort_order"
                        >
                            Sort Order
                        </label>


                        <input
                            type="number"
                            id="sort_order"
                            name="sort_order"
                            class="pc-input"
                            min="0"
                            step="1"
                            value="<?= e(
                                $editData['sort_order']
                                ?? 0
                            ) ?>"
                        >


                        <div class="pc-help">
                            Lower number = frontend par pehle.
                        </div>

                    </div>


                    <!-- FEATURED IMAGE -->

                    <div>

                        <label
                            class="pc-label"
                            for="featured_image_id"
                        >
                            Featured Image ID
                        </label>


                        <input
                            type="number"
                            id="featured_image_id"
                            name="featured_image_id"
                            class="pc-input"
                            min="1"
                            value="<?= e(
                                $editData['featured_image_id']
                                ?? ''
                            ) ?>"
                            placeholder="Media ID"
                        >


                        <div class="pc-help">
                            Existing media record ka ID.
                        </div>

                    </div>


                    <!-- BANNER -->

                    <div>

                        <label
                            class="pc-label"
                            for="banner_id"
                        >
                            Banner ID
                        </label>


                        <input
                            type="number"
                            id="banner_id"
                            name="banner_id"
                            class="pc-input"
                            min="1"
                            value="<?= e(
                                $editData['banner_id']
                                ?? ''
                            ) ?>"
                            placeholder="Media ID"
                        >


                        <div class="pc-help">
                            Existing media record ka ID.
                        </div>

                    </div>


                    <!-- CHECKBOXES -->

                    <div class="pc-form-full">

                        <div class="pc-check-row">


                            <label class="pc-check">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    <?= (
                                        !$editData
                                        ||
                                        (int)(
                                            $editData['status']
                                            ?? 0
                                        ) === 1
                                    )
                                        ? 'checked'
                                        : '' ?>
                                >

                                <span>
                                    Active Service
                                </span>

                            </label>


                            <label class="pc-check">

                                <input
                                    type="checkbox"
                                    name="featured"
                                    value="1"
                                    <?= (
                                        $editData
                                        &&
                                        (int)(
                                            $editData['featured']
                                            ?? 0
                                        ) === 1
                                    )
                                        ? 'checked'
                                        : '' ?>
                                >

                                <span>
                                    Featured Service
                                </span>

                            </label>


                        </div>

                    </div>


                </div>


                <!-- ACTIONS -->

                <div class="pc-modal-actions">


                    <button
                        type="button"
                        class="pc-btn pc-btn-light"
                        onclick="closeServiceModal()"
                    >

                        <i class="fa-solid fa-xmark"></i>

                        Cancel

                    </button>


                    <button
                        type="submit"
                        class="pc-btn pc-btn-primary"
                    >

                        <i class="fa-solid fa-floppy-disk"></i>

                        <?= $editData
                            ? 'Update Service'
                            : 'Save Service' ?>

                    </button>


                </div>


            </form>


        </div>

    </div>

</div>


<script>

/* =========================================================
   SERVICE MODAL
========================================================= */

function openServiceModal() {

    const modal =
        document.getElementById(
            'serviceModal'
        );

    if (modal) {
        modal.classList.add('show');
    }

}


function closeServiceModal() {

    const modal =
        document.getElementById(
            'serviceModal'
        );

    if (modal) {
        modal.classList.remove('show');
    }

}


/* =========================================================
   CLICK OUTSIDE MODAL
========================================================= */

document.addEventListener(
    'click',
    function(event) {

        const modal =
            document.getElementById(
                'serviceModal'
            );

        if (
            modal &&
            event.target === modal
        ) {
            closeServiceModal();
        }

    }
);


/* =========================================================
   ESC CLOSE
========================================================= */

document.addEventListener(
    'keydown',
    function(event) {

        if (event.key === 'Escape') {
            closeServiceModal();
        }

    }
);


/* =========================================================
   DELETE CONFIRMATION
========================================================= */

function confirmServiceDelete(name) {

    return confirm(
        "Delete this service?\n\n" +
        "Service: " + name +
        "\n\n" +
        "If this service has child services, " +
        "the delete operation will be blocked."
    );

}


/* =========================================================
   AUTO SLUG
========================================================= */

const serviceNameInput =
    document.getElementById(
        'service_name'
    );

const serviceSlugInput =
    document.getElementById(
        'service_slug'
    );


if (
    serviceNameInput &&
    serviceSlugInput
) {

    let slugManuallyEdited =
        serviceSlugInput.value.trim() !== '';


    serviceSlugInput.addEventListener(
        'input',
        function() {

            slugManuallyEdited = true;

        }
    );


    serviceNameInput.addEventListener(
        'input',
        function() {

            if (slugManuallyEdited) {
                return;
            }


            let value =
                this.value
                    .toLowerCase()
                    .trim();


            value =
                value
                    .replace(
                        /[^\p{L}\p{N}]+/gu,
                        '-'
                    )
                    .replace(
                        /^-+|-+$/g,
                        ''
                    );


            serviceSlugInput.value =
                value;

        }
    );

}


/* =========================================================
   SIDEBAR MOBILE
========================================================= */

function toggleSidebar() {

    const sidebar =
        document.querySelector(
            '.sidebar, .admin-sidebar, #sidebar'
        );

    if (sidebar) {
        sidebar.classList.toggle(
            'active'
        );
    }

}


/* =========================================================
   AUTO HIDE FLASH
========================================================= */

setTimeout(
    function() {

        document
            .querySelectorAll(
                '.pc-alert'
            )
            .forEach(
                function(alert) {

                    alert.style.transition =
                        'opacity .35s ease, transform .35s ease';

                    alert.style.opacity =
                        '0';

                    alert.style.transform =
                        'translateY(-5px)';

                    setTimeout(
                        function() {
                            alert.remove();
                        },
                        400
                    );

                }
            );

    },
    5000
);

</script>


</body>
</html>