<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Services / Extras Setup';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

/* ===========================
   HELPERS
=========================== */
function table_exists(PDO $pdo, string $tableName): bool
{
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name");
    $stmt->execute([':table_name' => $tableName]);
    return (int)$stmt->fetchColumn() > 0;
}

function column_exists(PDO $pdo, string $tableName, string $columnName): bool
{
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :table_name AND column_name = :column_name");
    $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
    return (int)$stmt->fetchColumn() > 0;
}

function service_is_used(PDO $pdo, int $serviceId): bool
{
    $checks = [
        ['table' => 'folio_transactions', 'column' => 'i_d'],
        ['table' => 'extras', 'column' => 'service_id'],
        ['table' => 'extra_charge_audit_log', 'column' => 'service_id'],
    ];

    foreach ($checks as $check) {
        if (!table_exists($pdo, $check['table']) || !column_exists($pdo, $check['table'], $check['column'])) {
            continue;
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$check['table']} WHERE {$check['column']} = :id");
        $stmt->execute([':id' => $serviceId]);
        if ((int)$stmt->fetchColumn() > 0) return true;
    }

    return false;
}

function category_has_services(PDO $pdo, int $categoryId): bool
{
    if (!table_exists($pdo, 'tblservices') || !column_exists($pdo, 'tblservices', 'category')) return false;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservices WHERE category = :category");
    $stmt->execute([':category' => $categoryId]);
    return (int)$stmt->fetchColumn() > 0;
}

function service_exists(PDO $pdo, int $serviceId): bool
{
    if ($serviceId <= 0 || !table_exists($pdo, 'tblservices')) return false;
    $where = 'id = :id';
    if (column_exists($pdo, 'tblservices', 'is_active')) {
        $where .= ' AND COALESCE(is_active,1)=1';
    }
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservices WHERE $where");
    $stmt->execute([':id' => $serviceId]);
    return (int)$stmt->fetchColumn() > 0;
}

function ensure_service_related_columns(PDO $pdo): void
{
    if (!table_exists($pdo, 'tblservices')) return;

    $columns = [
        'requires_related_fee' => "ALTER TABLE tblservices ADD COLUMN requires_related_fee TINYINT(1) NOT NULL DEFAULT 0 AFTER is_active",
        'related_service_id_1' => "ALTER TABLE tblservices ADD COLUMN related_service_id_1 INT UNSIGNED NULL AFTER requires_related_fee",
        'related_service_id_2' => "ALTER TABLE tblservices ADD COLUMN related_service_id_2 INT UNSIGNED NULL AFTER related_service_id_1",
    ];

    foreach ($columns as $column => $sql) {
        if (!column_exists($pdo, 'tblservices', $column)) {
            try { $pdo->exec($sql); } catch (Throwable $e) { /* handled by page errors where possible */ }
        }
    }
}

function ensure_subcategory_schema(PDO $pdo): void
{
    /*
       Optional third level: Category -> Subcategory -> Service.
       e.g. Category "Transfers and Activities" -> Subcategory "Cruises",
       "Helicopters", "Tours", "Game Drive". A service's subcategory is
       always optional - plenty of services will have none.
    */
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS tblservicesubcategory (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT,
                category_id INT NOT NULL,
                subcategory VARCHAR(100) NOT NULL,
                is_active TINYINT(1) NOT NULL DEFAULT 1,
                PRIMARY KEY (id),
                INDEX idx_svc_subcat_category (category_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    } catch (Throwable $e) { /* handled by page errors where possible */ }

    if (table_exists($pdo, 'tblservices') && !column_exists($pdo, 'tblservices', 'subcategory')) {
        try {
            $pdo->exec("ALTER TABLE tblservices ADD COLUMN subcategory INT UNSIGNED NULL AFTER category");
        } catch (Throwable $e) { /* handled by page errors where possible */ }
    }
}

function subcategory_has_services(PDO $pdo, int $subcategoryId): bool
{
    if (!table_exists($pdo, 'tblservices') || !column_exists($pdo, 'tblservices', 'subcategory')) return false;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservices WHERE subcategory = :subcategory");
    $stmt->execute([':subcategory' => $subcategoryId]);
    return (int)$stmt->fetchColumn() > 0;
}

function ensure_service_supplier_schema(PDO $pdo): void
{
    /*
       A service can have zero or many suppliers, each with its own rate.
       tblservice_suppliers is the junction: one row per (service, supplier)
       with the rate that supplier charges for that service.
    */
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS tblservice_suppliers (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT,
                service_id INT UNSIGNED NOT NULL,
                supplier_id INT UNSIGNED NOT NULL,
                rate DECIMAL(12,2) NOT NULL DEFAULT 0.00,
                is_active TINYINT(1) NOT NULL DEFAULT 1,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                UNIQUE KEY uq_service_supplier (service_id, supplier_id),
                INDEX idx_svc_supplier_service (service_id),
                INDEX idx_svc_supplier_supplier (supplier_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    } catch (Throwable $e) { /* handled by page errors where possible */ }
}

/**
 * Replace a service's supplier links with the given supplier_id => rate map.
 * Suppliers not in the map are removed; existing ones have their rate updated;
 * new ones are inserted. Only real, existing suppliers are linked.
 */
function sync_service_suppliers(PDO $pdo, int $serviceId, array $supplierPairs, bool $hasJunction, bool $hasSuppliers): void
{
    if ($serviceId <= 0 || !$hasJunction) return;

    // Keep only suppliers that actually exist (guards against stale POST ids).
    $validIds = [];
    if ($supplierPairs && $hasSuppliers) {
        $ids = array_keys($supplierPairs);
        $in = implode(',', array_map('intval', $ids));
        $rows = $pdo->query("SELECT id FROM inventory_suppliers WHERE id IN ($in)")->fetchAll(PDO::FETCH_COLUMN);
        $validIds = array_map('intval', $rows);
    }

    // Remove links no longer present.
    if ($validIds) {
        $in = implode(',', array_map('intval', $validIds));
        $del = $pdo->prepare("DELETE FROM tblservice_suppliers WHERE service_id = :sid AND supplier_id NOT IN ($in)");
        $del->execute([':sid' => $serviceId]);
    } else {
        $del = $pdo->prepare("DELETE FROM tblservice_suppliers WHERE service_id = :sid");
        $del->execute([':sid' => $serviceId]);
    }

    // Upsert each valid supplier + rate.
    if ($validIds) {
        $up = $pdo->prepare("
            INSERT INTO tblservice_suppliers (service_id, supplier_id, rate, is_active)
            VALUES (:sid, :supid, :rate, 1)
            ON DUPLICATE KEY UPDATE rate = VALUES(rate), is_active = 1
        ");
        foreach ($validIds as $sid) {
            $up->execute([
                ':sid'   => $serviceId,
                ':supid' => $sid,
                ':rate'  => isset($supplierPairs[$sid]) ? round((float)$supplierPairs[$sid], 2) : 0.0,
            ]);
        }
    }
}

$errors = [];
$success = '';

/* ===========================
   SETUP CHECK
=========================== */
$hasServicesTable = table_exists($pdo, 'tblservices');
$hasCategoryTable = table_exists($pdo, 'tblservicecategory');

if (!$hasServicesTable || !$hasCategoryTable) {
    $errors[] = 'Required tables are missing. Please create tblservices and tblservicecategory first.';
}

/* ===========================
   ENSURE COLUMNS
=========================== */
if ($hasServicesTable && !column_exists($pdo, 'tblservices', 'is_active')) {
    try {
        $pdo->exec("ALTER TABLE tblservices ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1 AFTER category");
    } catch (Throwable $e) {
        $errors[] = 'Could not add tblservices.is_active: ' . $e->getMessage();
    }
}

if ($hasCategoryTable && !column_exists($pdo, 'tblservicecategory', 'is_active')) {
    try {
        $pdo->exec("ALTER TABLE tblservicecategory ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1 AFTER category");
    } catch (Throwable $e) {
        $errors[] = 'Could not add tblservicecategory.is_active: ' . $e->getMessage();
    }
}

try { ensure_service_related_columns($pdo); } catch (Throwable $e) { $errors[] = 'Could not add related fee columns: ' . $e->getMessage(); }
try { ensure_subcategory_schema($pdo); } catch (Throwable $e) { $errors[] = 'Could not set up subcategories: ' . $e->getMessage(); }
try { ensure_service_supplier_schema($pdo); } catch (Throwable $e) { $errors[] = 'Could not set up service suppliers: ' . $e->getMessage(); }
$hasSubcategoryTable = table_exists($pdo, 'tblservicesubcategory');
$hasSuppliersTable = table_exists($pdo, 'inventory_suppliers');
$hasServiceSupplierTable = table_exists($pdo, 'tblservice_suppliers');

/* ===========================
   SAVE / UPDATE CATEGORY
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_category']) && $hasCategoryTable) {
    $categoryId = (int)($_POST['category_id'] ?? 0);
    $categoryName = trim((string)($_POST['category_name'] ?? ''));

    if ($categoryName === '') $errors[] = 'Category name is required.';

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservicecategory WHERE LOWER(TRIM(category)) = LOWER(TRIM(:category)) AND id <> :id");
            $stmt->execute([':category' => $categoryName, ':id' => $categoryId]);
            if ((int)$stmt->fetchColumn() > 0) throw new RuntimeException('A service category with this name already exists.');

            if ($categoryId > 0) {
                $stmt = $pdo->prepare("UPDATE tblservicecategory SET category = :category WHERE id = :id LIMIT 1");
                $stmt->execute([':category' => $categoryName, ':id' => $categoryId]);
                header('Location: services.php?category_updated=1'); exit;
            }

            $stmt = $pdo->prepare("INSERT INTO tblservicecategory (category) VALUES (:category)");
            $stmt->execute([':category' => $categoryName]);
            header('Location: services.php?category_saved=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   SAVE SERVICE
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_service']) && $hasServicesTable) {
    $serviceId = (int)($_POST['service_id'] ?? 0);
    $service = trim((string)($_POST['service'] ?? ''));
    $pricePerPerson = (float)($_POST['price_per_person'] ?? 0);
    $categoryId = (int)($_POST['category'] ?? 0);
    $subcategoryId = (int)($_POST['subcategory'] ?? 0);
    $requiresRelatedFee = isset($_POST['requires_related_fee']) ? 1 : 0;
    $related1 = (int)($_POST['related_service_id_1'] ?? 0);
    $related2 = (int)($_POST['related_service_id_2'] ?? 0);

    if ($service === '') $errors[] = 'Service name is required.';
    if ($pricePerPerson < 0) $errors[] = 'Price per person cannot be negative.';
    if ($categoryId <= 0) $errors[] = 'Please select a service category.';

    if ($subcategoryId > 0 && $hasSubcategoryTable) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservicesubcategory WHERE id = :id AND category_id = :category_id");
        $stmt->execute([':id' => $subcategoryId, ':category_id' => $categoryId]);
        if ((int)$stmt->fetchColumn() <= 0) $errors[] = 'Selected subcategory does not belong to the chosen category.';
    } else {
        $subcategoryId = 0;
    }

    if ($requiresRelatedFee) {
        if ($related1 <= 0 && $related2 <= 0) {
            $errors[] = 'Select at least one related service when this service requires a park fee or additional fee.';
        }
        if ($related1 > 0 && !service_exists($pdo, $related1)) $errors[] = 'Related Service 1 must be an active existing service.';
        if ($related2 > 0 && !service_exists($pdo, $related2)) $errors[] = 'Related Service 2 must be an active existing service.';
        if ($related1 > 0 && $related2 > 0 && $related1 === $related2) $errors[] = 'Related Service 1 and Related Service 2 cannot be the same.';
        if ($serviceId > 0 && ($related1 === $serviceId || $related2 === $serviceId)) $errors[] = 'A service cannot be linked to itself as a related fee.';
    } else {
        $related1 = 0;
        $related2 = 0;
    }

    if (!$errors) {
        try {
            /*
               Suppliers for this service: parallel arrays from the modal's
               repeatable rows. Each valid (supplier_id, rate) pair becomes a
               row in tblservice_suppliers. Zero rows is allowed - a service
               may have no supplier.
            */
            $supplierIds   = $_POST['supplier_id']   ?? [];
            $supplierRates = $_POST['supplier_rate'] ?? [];
            if (!is_array($supplierIds))   $supplierIds = [];
            if (!is_array($supplierRates)) $supplierRates = [];

            $supplierPairs = [];   // supplier_id => rate (deduped, last wins)
            foreach ($supplierIds as $idx => $sid) {
                $sid = (int)$sid;
                if ($sid <= 0) continue;
                $rate = isset($supplierRates[$idx]) ? (float)$supplierRates[$idx] : 0.0;
                if ($rate < 0) $rate = 0.0;
                $supplierPairs[$sid] = round($rate, 2);
            }

            if ($serviceId > 0) {
                $stmt = $pdo->prepare("\n                    UPDATE tblservices\n                    SET service = :service,\n                        price_per_person = :price_per_person,\n                        category = :category,\n                        subcategory = :subcategory,\n                        requires_related_fee = :requires_related_fee,\n                        related_service_id_1 = :related_service_id_1,\n                        related_service_id_2 = :related_service_id_2\n                    WHERE id = :id\n                ");
                $stmt->execute([
                    ':service' => $service,
                    ':price_per_person' => round($pricePerPerson, 2),
                    ':category' => $categoryId,
                    ':subcategory' => $subcategoryId > 0 ? $subcategoryId : null,
                    ':requires_related_fee' => $requiresRelatedFee,
                    ':related_service_id_1' => $related1 > 0 ? $related1 : null,
                    ':related_service_id_2' => $related2 > 0 ? $related2 : null,
                    ':id' => $serviceId,
                ]);
                sync_service_suppliers($pdo, $serviceId, $supplierPairs, $hasServiceSupplierTable, $hasSuppliersTable);
                header('Location: services.php?updated=1'); exit;
            }

            $stmt = $pdo->prepare("\n                INSERT INTO tblservices\n                    (service, price_per_person, category, subcategory, requires_related_fee, related_service_id_1, related_service_id_2)\n                VALUES\n                    (:service, :price_per_person, :category, :subcategory, :requires_related_fee, :related_service_id_1, :related_service_id_2)\n            ");
            $stmt->execute([
                ':service' => $service,
                ':price_per_person' => round($pricePerPerson, 2),
                ':category' => $categoryId,
                ':subcategory' => $subcategoryId > 0 ? $subcategoryId : null,
                ':requires_related_fee' => $requiresRelatedFee,
                ':related_service_id_1' => $related1 > 0 ? $related1 : null,
                ':related_service_id_2' => $related2 > 0 ? $related2 : null,
            ]);
            $newServiceId = (int)$pdo->lastInsertId();
            sync_service_suppliers($pdo, $newServiceId, $supplierPairs, $hasServiceSupplierTable, $hasSuppliersTable);
            header('Location: services.php?saved=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   DELETE / INACTIVATE SERVICE
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_service']) && $hasServicesTable) {
    $serviceId = (int)($_POST['service_id'] ?? 0);
    if ($serviceId <= 0) $errors[] = 'Invalid service selected.';

    if (!$errors) {
        try {
            if (service_is_used($pdo, $serviceId)) {
                $stmt = $pdo->prepare("UPDATE tblservices SET is_active = 0 WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $serviceId]);
                header('Location: services.php?service_inactivated=1'); exit;
            }
            $stmt = $pdo->prepare("DELETE FROM tblservices WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $serviceId]);
            header('Location: services.php?deleted=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   REACTIVATE SERVICE
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reactivate_service']) && $hasServicesTable) {
    $serviceId = (int)($_POST['service_id'] ?? 0);
    if ($serviceId <= 0) $errors[] = 'Invalid service selected.';

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("UPDATE tblservices SET is_active = 1 WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $serviceId]);
            header('Location: services.php?service_reactivated=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   DELETE / INACTIVATE CATEGORY
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_category']) && $hasCategoryTable) {
    $categoryId = (int)($_POST['category_id'] ?? 0);
    if ($categoryId <= 0) $errors[] = 'Invalid category selected.';

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservices WHERE category = :category_id");
            $stmt->execute([':category_id' => $categoryId]);
            $linkedServices = (int)$stmt->fetchColumn();

            if ($linkedServices > 0) {
                $stmt = $pdo->prepare("UPDATE tblservicecategory SET is_active = 0 WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $categoryId]);
                header('Location: services.php?category_inactivated=1'); exit;
            }

            $stmt = $pdo->prepare("DELETE FROM tblservicecategory WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $categoryId]);
            header('Location: services.php?category_deleted=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   REACTIVATE CATEGORY
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reactivate_category']) && $hasCategoryTable) {
    $categoryId = (int)($_POST['category_id'] ?? 0);
    if ($categoryId <= 0) $errors[] = 'Invalid category selected.';

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("UPDATE tblservicecategory SET is_active = 1 WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $categoryId]);
            header('Location: services.php?category_reactivated=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   SAVE / UPDATE SUBCATEGORY
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_subcategory']) && $hasSubcategoryTable) {
    $subcategoryId = (int)($_POST['subcategory_id'] ?? 0);
    $subcategoryCategoryId = (int)($_POST['subcategory_category_id'] ?? 0);
    $subcategoryName = trim((string)($_POST['subcategory_name'] ?? ''));

    if ($subcategoryCategoryId <= 0) $errors[] = 'Please select the parent category for this subcategory.';
    if ($subcategoryName === '') $errors[] = 'Subcategory name is required.';

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblservicesubcategory WHERE category_id = :category_id AND LOWER(TRIM(subcategory)) = LOWER(TRIM(:subcategory)) AND id <> :id");
            $stmt->execute([':category_id' => $subcategoryCategoryId, ':subcategory' => $subcategoryName, ':id' => $subcategoryId]);
            if ((int)$stmt->fetchColumn() > 0) throw new RuntimeException('This category already has a subcategory with this name.');

            if ($subcategoryId > 0) {
                $stmt = $pdo->prepare("UPDATE tblservicesubcategory SET category_id = :category_id, subcategory = :subcategory WHERE id = :id LIMIT 1");
                $stmt->execute([':category_id' => $subcategoryCategoryId, ':subcategory' => $subcategoryName, ':id' => $subcategoryId]);
                header('Location: services.php?subcategory_updated=1'); exit;
            }

            $stmt = $pdo->prepare("INSERT INTO tblservicesubcategory (category_id, subcategory) VALUES (:category_id, :subcategory)");
            $stmt->execute([':category_id' => $subcategoryCategoryId, ':subcategory' => $subcategoryName]);
            header('Location: services.php?subcategory_saved=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   DELETE / INACTIVATE SUBCATEGORY
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_subcategory']) && $hasSubcategoryTable) {
    $subcategoryId = (int)($_POST['subcategory_id'] ?? 0);
    if ($subcategoryId <= 0) $errors[] = 'Invalid subcategory selected.';

    if (!$errors) {
        try {
            if (subcategory_has_services($pdo, $subcategoryId)) {
                $stmt = $pdo->prepare("UPDATE tblservicesubcategory SET is_active = 0 WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $subcategoryId]);
                header('Location: services.php?subcategory_inactivated=1'); exit;
            }
            $stmt = $pdo->prepare("DELETE FROM tblservicesubcategory WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $subcategoryId]);
            header('Location: services.php?subcategory_deleted=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   REACTIVATE SUBCATEGORY
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reactivate_subcategory']) && $hasSubcategoryTable) {
    $subcategoryId = (int)($_POST['subcategory_id'] ?? 0);
    if ($subcategoryId <= 0) $errors[] = 'Invalid subcategory selected.';

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("UPDATE tblservicesubcategory SET is_active = 1 WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $subcategoryId]);
            header('Location: services.php?subcategory_reactivated=1'); exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

/* ===========================
   FLASH MESSAGES
=========================== */
if (isset($_GET['saved'])) $success = 'Service added successfully.';
if (isset($_GET['updated'])) $success = 'Service updated successfully.';
if (isset($_GET['deleted'])) $success = 'Service deleted successfully.';
if (isset($_GET['category_saved'])) $success = 'Service category added successfully.';
if (isset($_GET['category_updated'])) $success = 'Service category updated successfully.';
if (isset($_GET['service_inactivated'])) $success = 'Service has previous usage, so it was marked inactive instead of deleted.';
if (isset($_GET['service_reactivated'])) $success = 'Service reactivated successfully.';
if (isset($_GET['category_deleted'])) $success = 'Service category deleted successfully.';
if (isset($_GET['category_inactivated'])) $success = 'Category is linked to services, so it was marked inactive instead of deleted.';
if (isset($_GET['category_reactivated'])) $success = 'Service category reactivated successfully.';
if (isset($_GET['subcategory_saved'])) $success = 'Subcategory added successfully.';
if (isset($_GET['subcategory_updated'])) $success = 'Subcategory updated successfully.';
if (isset($_GET['subcategory_deleted'])) $success = 'Subcategory deleted successfully.';
if (isset($_GET['subcategory_inactivated'])) $success = 'Subcategory is linked to services, so it was marked inactive instead of deleted.';
if (isset($_GET['subcategory_reactivated'])) $success = 'Subcategory reactivated successfully.';

/* ===========================
   LOAD DATA
=========================== */
$categories = [];
$subcategories = [];
$services = [];
$activeServiceOptions = [];
$selectedCategory = (int)($_GET['category'] ?? 0);
$selectedSubcategory = (int)($_GET['subcategory'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));

if ($hasCategoryTable) {
    $categories = $pdo->query("\n        SELECT c.id, c.category, COALESCE(c.is_active, 1) AS is_active,\n               (SELECT COUNT(*) FROM tblservices s WHERE s.category = c.id) AS linked_services\n        FROM tblservicecategory c\n        ORDER BY COALESCE(c.is_active, 1) DESC, c.category ASC\n    ")->fetchAll(PDO::FETCH_ASSOC);
}

if ($hasSubcategoryTable) {
    $subcategories = $pdo->query("\n        SELECT sc.id, sc.category_id, sc.subcategory, COALESCE(sc.is_active, 1) AS is_active,\n               c.category AS category_name,\n               (SELECT COUNT(*) FROM tblservices s WHERE s.subcategory = sc.id) AS linked_services\n        FROM tblservicesubcategory sc\n        LEFT JOIN tblservicecategory c ON c.id = sc.category_id\n        ORDER BY c.category ASC, COALESCE(sc.is_active, 1) DESC, sc.subcategory ASC\n    ")->fetchAll(PDO::FETCH_ASSOC);
}

if ($hasServicesTable) {
    $activeServiceOptions = $pdo->query("\n        SELECT id, service, price_per_person\n        FROM tblservices\n        WHERE COALESCE(is_active,1)=1\n        ORDER BY service ASC\n    ")->fetchAll(PDO::FETCH_ASSOC);

    $subcategorySelectSql = $hasSubcategoryTable
        ? "sc.subcategory AS subcategory_name, COALESCE(sc.is_active, 1) AS subcategory_is_active,"
        : "NULL AS subcategory_name, 1 AS subcategory_is_active,";
    $subcategoryJoinSql = $hasSubcategoryTable
        ? "LEFT JOIN tblservicesubcategory sc ON sc.id = s.subcategory"
        : "";

    $sql = "\n        SELECT\n            s.id, s.service, s.price_per_person, s.category AS category_id, s.subcategory AS subcategory_id,\n            COALESCE(s.is_active, 1) AS is_active, 0 AS is_used,\n            COALESCE(s.requires_related_fee,0) AS requires_related_fee,\n            s.related_service_id_1, s.related_service_id_2,\n            c.category AS category_name, COALESCE(c.is_active, 1) AS category_is_active,\n            {$subcategorySelectSql}\n            r1.service AS related_service_1_name, r1.price_per_person AS related_service_1_price,\n            r2.service AS related_service_2_name, r2.price_per_person AS related_service_2_price\n        FROM tblservices s\n        LEFT JOIN tblservicecategory c ON c.id = s.category\n        {$subcategoryJoinSql}\n        LEFT JOIN tblservices r1 ON r1.id = s.related_service_id_1\n        LEFT JOIN tblservices r2 ON r2.id = s.related_service_id_2\n        WHERE 1 = 1\n    ";

    $params = [];
    if ($selectedCategory > 0) {
        $sql .= " AND s.category = :category ";
        $params[':category'] = $selectedCategory;
    }
    if ($selectedSubcategory > 0 && $hasSubcategoryTable) {
        $sql .= " AND s.subcategory = :subcategory ";
        $params[':subcategory'] = $selectedSubcategory;
    }
    if ($q !== '') {
        /*
           Do not reuse the same named PDO parameter more than once.
           Some servers run PDO with native prepares and repeated :q causes
           HY093 / HTTP 500 when searching. Use separate placeholders.
        */
        $sql .= " AND (s.service LIKE :q_service OR r1.service LIKE :q_related1 OR r2.service LIKE :q_related2) ";
        $params[':q_service'] = '%' . $q . '%';
        $params[':q_related1'] = '%' . $q . '%';
        $params[':q_related2'] = '%' . $q . '%';
    }
    $sql .= " ORDER BY c.category ASC, s.service ASC ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($services as &$svcRow) {
        $svcRow['is_used'] = service_is_used($pdo, (int)$svcRow['id']) ? 1 : 0;
        $svcRow['suppliers'] = [];
    }
    unset($svcRow);

    /* Attach linked suppliers (with rates) to each service in one query. */
    if ($services && $hasServiceSupplierTable && $hasSuppliersTable) {
        $svcIds = array_map(function ($r) { return (int)$r['id']; }, $services);
        $in = implode(',', $svcIds);
        $linkRows = $pdo->query("
            SELECT ss.service_id, ss.supplier_id, ss.rate,
                   sup.supplier_name, COALESCE(sup.is_active,1) AS supplier_is_active
            FROM tblservice_suppliers ss
            LEFT JOIN inventory_suppliers sup ON sup.id = ss.supplier_id
            WHERE ss.service_id IN ($in) AND COALESCE(ss.is_active,1) = 1
            ORDER BY sup.supplier_name ASC
        ")->fetchAll(PDO::FETCH_ASSOC);

        $bySvc = [];
        foreach ($linkRows as $lr) {
            $bySvc[(int)$lr['service_id']][] = $lr;
        }
        foreach ($services as &$svcRow) {
            $svcRow['suppliers'] = $bySvc[(int)$svcRow['id']] ?? [];
        }
        unset($svcRow);
    }
}

/* Active suppliers for the service modal dropdowns. */
$supplierOptions = [];
if ($hasSuppliersTable) {
    $supplierOptions = $pdo->query("
        SELECT id, supplier_name
        FROM inventory_suppliers
        WHERE COALESCE(is_active,1) = 1
        ORDER BY supplier_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
}

require_once __DIR__ . '/../../includes/header.php';
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-ui-checks-grid"></i> Extras Setup</div>
            <div class="hero-title mt-2">Services / Extras</div>
            <div class="hero-subtitle mt-2">
                Maintain chargeable services used when posting extras to guest, room, or master folios. Services can now automatically add up to two linked fees such as park fees.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <button type="button" class="btn btn-light me-2" data-bs-toggle="modal" data-bs-target="#categoryModal" id="btnNewCategory"><i class="bi bi-folder-plus me-2"></i>Add Category</button>
            <button type="button" class="btn btn-outline-light me-2" data-bs-toggle="modal" data-bs-target="#manageCategoriesModal"><i class="bi bi-pencil-square me-2"></i>Edit Categories</button>
            <button type="button" class="btn btn-light me-2" data-bs-toggle="modal" data-bs-target="#subcategoryModal" id="btnNewSubcategory"><i class="bi bi-diagram-2 me-2"></i>Add Subcategory</button>
            <button type="button" class="btn btn-outline-light me-2" data-bs-toggle="modal" data-bs-target="#manageSubcategoriesModal"><i class="bi bi-pencil-square me-2"></i>Edit Subcategories</button>
            <button type="button" class="btn btn-outline-light" data-bs-toggle="modal" data-bs-target="#serviceModal" id="btnNewService"><i class="bi bi-plus-circle me-2"></i>Add Service</button>
        </div>
    </div>
</div>

<?php if ($success): ?><div class="alert alert-success"><?php echo h($success); ?></div><?php endif; ?>
<?php if ($errors): ?>
    <div class="alert alert-danger"><div class="fw-bold mb-2">Please fix the following:</div><ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<?php if (!$hasServicesTable || !$hasCategoryTable): ?>
    <div class="card panel-card">
        <div class="card-body">
            <h5>Required SQL</h5>
            <pre class="bg-light border rounded p-3 mb-0">CREATE TABLE tblservicecategory (
    id INT NOT NULL AUTO_INCREMENT,
    category VARCHAR(50) NOT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    PRIMARY KEY (id)
);

CREATE TABLE tblservices (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    service VARCHAR(150) NOT NULL,
    price_per_person DECIMAL(12,2) NOT NULL DEFAULT 0.00,
    category INT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    requires_related_fee TINYINT(1) NOT NULL DEFAULT 0,
    related_service_id_1 INT UNSIGNED NULL,
    related_service_id_2 INT UNSIGNED NULL,
    PRIMARY KEY (id)
);</pre>
        </div>
    </div>
<?php else: ?>

<div class="row g-4 mb-4">
    <div class="col-md-4"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-list-check"></i></div><div><div class="metric-label">Total Services</div><div class="metric-value"><?php echo count($services); ?></div></div></div></div>
    <div class="col-md-4"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-folder2-open"></i></div><div><div class="metric-label">Categories</div><div class="metric-value"><?php echo count($categories); ?></div></div></div></div>
    <div class="col-md-4"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-cash-coin"></i></div><div><div class="metric-label">Average Price</div><div class="metric-value"><?php $avg=0; if($services){$sum=0; foreach($services as $s){$sum+=(float)$s['price_per_person'];} $avg=$sum/count($services);} echo money_fmt($avg); ?></div></div></div></div>
</div>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label">Category</label>
                <select name="category" id="filter_category" class="form-select">
                    <option value="0">All categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo (int)$cat['id']; ?>" <?php echo $selectedCategory === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo h($cat['category']); ?><?php echo (int)($cat['is_active'] ?? 1) === 0 ? ' ✕ inactive' : ''; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Subcategory</label>
                <select name="subcategory" id="filter_subcategory" class="form-select">
                    <option value="0">All subcategories</option>
                    <?php foreach ($subcategories as $sub): ?>
                        <option value="<?php echo (int)$sub['id']; ?>" data-category-id="<?php echo (int)$sub['category_id']; ?>" <?php echo $selectedSubcategory === (int)$sub['id'] ? 'selected' : ''; ?>><?php echo h($sub['category_name'] . ' › ' . $sub['subcategory']); ?><?php echo (int)($sub['is_active'] ?? 1) === 0 ? ' ✕ inactive' : ''; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4"><label class="form-label">Search Service</label><input type="text" name="q" class="form-control" value="<?php echo h($q); ?>" placeholder="Search service name or linked fee"></div>
            <div class="col-md-2 d-grid"><button class="btn btn-primary"><i class="bi bi-search me-2"></i>Filter</button></div>
        </form>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Service List</h5>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#serviceModal" id="btnNewServiceTop"><i class="bi bi-plus-circle me-2"></i>Add Service</button>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead><tr><th style="width:70px;">#</th><th>Service</th><th>Category</th><th>Required Extra / Park Fee</th><th>Suppliers &amp; Rates</th><th class="text-end">Price Per Person</th><th class="text-end" style="width:190px;">Actions</th></tr></thead>
                <tbody>
                    <?php if (!$services): ?>
                        <tr><td colspan="7" class="text-center text-muted py-4">No services found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($services as $index => $service): ?>
                            <tr class="<?php echo (int)($service['is_active'] ?? 1) === 0 ? 'inactive-row' : ''; ?>">
                                <td><?php echo $index + 1; ?></td>
                                <td><div class="data-stack"><strong><?php echo h($service['service']); ?></strong><?php if ((int)($service['is_active'] ?? 1) === 0): ?><span class="inactive-cross ms-2"><i class="bi bi-x-circle-fill"></i> Inactive</span><?php endif; ?><small>Service ID: <?php echo (int)$service['id']; ?><?php echo (int)($service['is_used'] ?? 0) === 1 ? ' • Used' : ' • Unused'; ?></small></div></td>
                                <td><?php if (!empty($service['category_name'])): ?><span class="badge text-bg-light border"><?php echo h($service['category_name']); ?></span><?php if ((int)($service['category_is_active'] ?? 1) === 0): ?><span class="badge text-bg-danger ms-1"><i class="bi bi-x-circle"></i> Category inactive</span><?php endif; ?><?php if (!empty($service['subcategory_name'])): ?><div class="small text-muted mt-1"><i class="bi bi-arrow-return-right"></i> <?php echo h($service['subcategory_name']); ?><?php if ((int)($service['subcategory_is_active'] ?? 1) === 0): ?> <span class="text-danger">(inactive)</span><?php endif; ?></div><?php endif; ?><?php else: ?><span class="badge text-bg-warning text-dark">No Category</span><?php endif; ?></td>
                                <td>
                                    <?php if ((int)($service['requires_related_fee'] ?? 0) === 1): ?>
                                        <span class="badge text-bg-info mb-1">Requires extra</span><br>
                                        <?php if (!empty($service['related_service_1_name'])): ?><small class="d-block">1. <?php echo h($service['related_service_1_name']); ?> (<?php echo money_fmt($service['related_service_1_price']); ?>)</small><?php endif; ?>
                                        <?php if (!empty($service['related_service_2_name'])): ?><small class="d-block">2. <?php echo h($service['related_service_2_name']); ?> (<?php echo money_fmt($service['related_service_2_price']); ?>)</small><?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted small">None</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($service['suppliers'])): ?>
                                        <?php foreach ($service['suppliers'] as $sup): ?>
                                            <small class="d-block">
                                                <i class="bi bi-truck text-muted"></i>
                                                <?php echo h($sup['supplier_name'] ?? ('Supplier #' . (int)$sup['supplier_id'])); ?>
                                                <span class="fw-bold">(<?php echo money_fmt($sup['rate']); ?>)</span>
                                                <?php if ((int)($sup['supplier_is_active'] ?? 1) === 0): ?><span class="text-danger">(inactive)</span><?php endif; ?>
                                            </small>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <span class="text-muted small">None</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end fw-bold"><?php echo money_fmt($service['price_per_person']); ?></td>
                                <td class="text-end">
                                    <div class="d-inline-flex gap-2 justify-content-end">
                                        <button type="button" class="btn btn-sm btn-outline-primary btn-edit-service" data-bs-toggle="modal" data-bs-target="#serviceModal" data-id="<?php echo (int)$service['id']; ?>" data-service="<?php echo h($service['service']); ?>" data-price="<?php echo h($service['price_per_person']); ?>" data-category="<?php echo (int)$service['category_id']; ?>" data-subcategory="<?php echo (int)($service['subcategory_id'] ?? 0); ?>" data-requires-related="<?php echo (int)($service['requires_related_fee'] ?? 0); ?>" data-related1="<?php echo (int)($service['related_service_id_1'] ?? 0); ?>" data-related2="<?php echo (int)($service['related_service_id_2'] ?? 0); ?>" data-suppliers='<?php echo h(json_encode(array_map(function ($s) { return ['supplier_id' => (int)$s['supplier_id'], 'rate' => (float)$s['rate']]; }, $service['suppliers'] ?? []), JSON_HEX_APOS | JSON_HEX_QUOT)); ?>'><i class="bi bi-pencil-square me-1"></i>Edit</button>
                                        <button type="button" class="btn btn-sm btn-outline-danger btn-delete-service" data-bs-toggle="modal" data-bs-target="#deleteServiceModal" data-id="<?php echo (int)$service['id']; ?>" data-service="<?php echo h($service['service']); ?>" data-used="<?php echo (int)($service['is_used'] ?? 0); ?>"><?php if ((int)($service['is_used'] ?? 0) === 1): ?><i class="bi bi-x-circle me-1"></i>Deactivate<?php else: ?><i class="bi bi-trash me-1"></i>Delete<?php endif; ?></button>
                                        <?php if ((int)($service['is_active'] ?? 1) === 0): ?><form method="post" class="d-inline"><input type="hidden" name="service_id" value="<?php echo (int)$service['id']; ?>"><button type="submit" name="reactivate_service" value="1" class="btn btn-sm btn-outline-success"><i class="bi bi-check-circle me-1"></i>Reactivate</button></form><?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- SERVICE MODAL -->
<div class="modal fade" id="serviceModal" tabindex="-1" aria-labelledby="serviceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form method="post" class="modal-content">
            <div class="modal-header pro-header"><h5 class="modal-title" id="serviceModalLabel">Add Service</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button></div>
            <div class="modal-body">
                <input type="hidden" name="service_id" id="service_id" value="0">
                <div class="row g-3">
                    <div class="col-md-6"><label class="form-label">Service Name</label><input type="text" name="service" id="service_name" class="form-control" placeholder="e.g. Airport Transfer, Sunset Cruise, Park Fee" required></div>
                    <div class="col-md-6"><label class="form-label">Category</label><select name="category" id="service_category" class="form-select" required><option value="">Select category</option><?php foreach ($categories as $cat): ?><option value="<?php echo (int)$cat['id']; ?>"><?php echo h($cat['category']); ?><?php echo (int)($cat['is_active'] ?? 1) === 0 ? ' ✕ inactive' : ''; ?></option><?php endforeach; ?></select><div class="form-hint mt-1">This controls which services appear in the Extras modal.</div></div>
                    <div class="col-md-6"><label class="form-label">Subcategory (optional)</label><select name="subcategory" id="service_subcategory" class="form-select"><option value="0">No subcategory</option><?php foreach ($subcategories as $sub): ?><option value="<?php echo (int)$sub['id']; ?>" data-category-id="<?php echo (int)$sub['category_id']; ?>"><?php echo h($sub['category_name'] . ' › ' . $sub['subcategory']); ?><?php echo (int)($sub['is_active'] ?? 1) === 0 ? ' ✕ inactive' : ''; ?></option><?php endforeach; ?></select><div class="form-hint mt-1">Options are filtered to the selected category. Useful for reporting, e.g. Transfers &amp; Activities &rarr; Cruises, Helicopters, Tours, Game Drive.</div></div>
                    <div class="col-md-4"><label class="form-label">Price Per Person</label><input type="number" step="0.01" min="0" name="price_per_person" id="service_price" class="form-control" value="0.00" required></div>
                    <div class="col-md-8">
                        <label class="form-label d-block">Park Fee / Additional Fee</label>
                        <div class="form-check form-switch mt-2">
                            <input class="form-check-input" type="checkbox" name="requires_related_fee" id="requires_related_fee" value="1">
                            <label class="form-check-label fw-semibold" for="requires_related_fee">This service requires another fee/service line when sold</label>
                        </div>
                        <div class="form-hint mt-1">Example: Sunset Cruise can automatically add Park Fee. Maximum two related services.</div>
                    </div>
                    <div class="col-md-6 related-fee-block d-none"><label class="form-label">Related Service 1</label><select name="related_service_id_1" id="related_service_id_1" class="form-select service-search-select"><option value="0">Search/select related service</option><?php foreach ($activeServiceOptions as $opt): ?><option value="<?php echo (int)$opt['id']; ?>"><?php echo h($opt['service']); ?> - <?php echo money_fmt($opt['price_per_person']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-6 related-fee-block d-none"><label class="form-label">Related Service 2</label><select name="related_service_id_2" id="related_service_id_2" class="form-select service-search-select"><option value="0">Search/select optional related service</option><?php foreach ($activeServiceOptions as $opt): ?><option value="<?php echo (int)$opt['id']; ?>"><?php echo h($opt['service']); ?> - <?php echo money_fmt($opt['price_per_person']); ?></option><?php endforeach; ?></select></div>

                    <div class="col-12"><hr class="my-1"></div>
                    <div class="col-12">
                        <label class="form-label d-block mb-1"><i class="bi bi-truck me-1"></i>Suppliers &amp; Rates</label>
                        <div class="form-hint mb-2">A service can have no supplier, one, or several - each with its own rate. Leave empty if none.</div>
                        <?php if (!$hasSuppliersTable): ?>
                            <div class="alert alert-warning py-2 mb-0 small">No suppliers table found. Add suppliers on the Suppliers page first.</div>
                        <?php else: ?>
                            <div id="supplierRows"></div>
                            <button type="button" class="btn btn-sm btn-outline-secondary mt-2" id="btnAddSupplierRow"><i class="bi bi-plus-circle me-1"></i>Add Supplier</button>
                            <!-- Template row (cloned by JS). Kept out of the form with no name attrs until cloned. -->
                            <template id="supplierRowTemplate">
                                <div class="row g-2 align-items-end supplier-row mt-1">
                                    <div class="col-md-7">
                                        <label class="form-label small mb-1">Supplier</label>
                                        <select class="form-select supplier-select" data-name="supplier_id">
                                            <option value="0">Select supplier</option>
                                            <?php foreach ($supplierOptions as $sup): ?>
                                                <option value="<?php echo (int)$sup['id']; ?>"><?php echo h($sup['supplier_name']); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small mb-1">Rate</label>
                                        <input type="number" step="0.01" min="0" class="form-control supplier-rate" data-name="supplier_rate" value="0.00">
                                    </div>
                                    <div class="col-md-1 d-grid">
                                        <button type="button" class="btn btn-outline-danger btn-remove-supplier-row" title="Remove"><i class="bi bi-x-lg"></i></button>
                                    </div>
                                </div>
                            </template>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" name="save_service" value="1" class="btn btn-primary"><i class="bi bi-save me-2"></i>Save Service</button></div>
        </form>
    </div>
</div>

<!-- CATEGORY MODAL -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
    <div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header pro-header"><h5 class="modal-title" id="categoryModalLabel">Add Service Category</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><input type="hidden" name="category_id" id="category_id" value="0"><label class="form-label">Category Name</label><input type="text" name="category_name" id="category_name" class="form-control" placeholder="e.g. Transfers, Activities, Laundry" required><div class="form-hint mt-1">Renaming a category keeps all existing services linked to it.</div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" name="save_category" value="1" class="btn btn-primary" id="categorySaveBtn"><i class="bi bi-save me-2"></i>Save Category</button></div></form></div>
</div>

<!-- MANAGE CATEGORIES MODAL -->
<div class="modal fade" id="manageCategoriesModal" tabindex="-1" aria-labelledby="manageCategoriesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content"><div class="modal-header pro-header"><h5 class="modal-title" id="manageCategoriesModalLabel">Edit Service Categories</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body p-0"><div class="table-responsive manage-categories-table"><table class="table table-modern align-middle mb-0"><thead><tr><th style="width:80px;">#</th><th>Category</th><th class="text-end">Linked Services</th><th>Status</th><th class="text-end" style="width:260px;">Action</th></tr></thead><tbody><?php if (!$categories): ?><tr><td colspan="5" class="text-center text-muted py-4">No categories found.</td></tr><?php else: ?><?php foreach ($categories as $index => $cat): ?><tr class="<?php echo (int)($cat['is_active'] ?? 1) === 0 ? 'inactive-row' : ''; ?>"><td><?php echo $index + 1; ?></td><td><strong><?php echo h($cat['category']); ?></strong><?php if ((int)($cat['is_active'] ?? 1) === 0): ?><span class="inactive-cross ms-2"><i class="bi bi-x-circle-fill"></i> Inactive</span><?php endif; ?><div class="small text-muted">Category ID: <?php echo (int)$cat['id']; ?></div></td><td class="text-end fw-bold"><?php echo (int)($cat['linked_services'] ?? 0); ?></td><td><?php if ((int)($cat['is_active'] ?? 1) === 1): ?><span class="badge text-bg-success">Active</span><?php else: ?><span class="badge text-bg-danger"><i class="bi bi-x-circle me-1"></i>Inactive</span><?php endif; ?></td><td class="text-end"><div class="d-inline-flex gap-2 justify-content-end flex-wrap"><button type="button" class="btn btn-sm btn-outline-primary btn-edit-category" data-bs-toggle="modal" data-bs-target="#categoryModal" data-id="<?php echo (int)$cat['id']; ?>" data-category="<?php echo h($cat['category']); ?>"><i class="bi bi-pencil-square me-1"></i>Edit</button><button type="button" class="btn btn-sm btn-outline-danger btn-delete-category" data-bs-toggle="modal" data-bs-target="#deleteCategoryModal" data-id="<?php echo (int)$cat['id']; ?>" data-category="<?php echo h($cat['category']); ?>" data-linked="<?php echo (int)($cat['linked_services'] ?? 0); ?>"><?php if ((int)($cat['linked_services'] ?? 0) > 0): ?><i class="bi bi-x-circle me-1"></i>Deactivate<?php else: ?><i class="bi bi-trash me-1"></i>Delete<?php endif; ?></button><?php if ((int)($cat['is_active'] ?? 1) === 0): ?><form method="post" class="d-inline"><input type="hidden" name="category_id" value="<?php echo (int)$cat['id']; ?>"><button type="submit" name="reactivate_category" value="1" class="btn btn-sm btn-outline-success"><i class="bi bi-check-circle me-1"></i>Reactivate</button></form><?php endif; ?></div></td></tr><?php endforeach; ?><?php endif; ?></tbody></table></div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button><button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal" id="btnAddCategoryFromManage"><i class="bi bi-folder-plus me-2"></i>Add Category</button></div></div></div>
</div>

<!-- SUBCATEGORY MODAL -->
<div class="modal fade" id="subcategoryModal" tabindex="-1" aria-labelledby="subcategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header pro-header"><h5 class="modal-title" id="subcategoryModalLabel">Add Subcategory</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><input type="hidden" name="subcategory_id" id="subcategory_id" value="0"><label class="form-label">Parent Category</label><select name="subcategory_category_id" id="subcategory_category_id" class="form-select mb-3" required><option value="">Select category</option><?php foreach ($categories as $cat): ?><option value="<?php echo (int)$cat['id']; ?>"><?php echo h($cat['category']); ?><?php echo (int)($cat['is_active'] ?? 1) === 0 ? ' ✕ inactive' : ''; ?></option><?php endforeach; ?></select><label class="form-label">Subcategory Name</label><input type="text" name="subcategory_name" id="subcategory_name" class="form-control" placeholder="e.g. Cruises, Helicopters, Tours, Game Drive" required><div class="form-hint mt-1">Optional third level for reporting - services can still be saved with no subcategory.</div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" name="save_subcategory" value="1" class="btn btn-primary" id="subcategorySaveBtn"><i class="bi bi-save me-2"></i>Save Subcategory</button></div></form></div>
</div>

<!-- MANAGE SUBCATEGORIES MODAL -->
<div class="modal fade" id="manageSubcategoriesModal" tabindex="-1" aria-labelledby="manageSubcategoriesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content"><div class="modal-header pro-header"><h5 class="modal-title" id="manageSubcategoriesModalLabel">Edit Subcategories</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body p-0"><div class="table-responsive manage-categories-table"><table class="table table-modern align-middle mb-0"><thead><tr><th style="width:80px;">#</th><th>Category</th><th>Subcategory</th><th class="text-end">Linked Services</th><th>Status</th><th class="text-end" style="width:260px;">Action</th></tr></thead><tbody><?php if (!$subcategories): ?><tr><td colspan="6" class="text-center text-muted py-4">No subcategories found.</td></tr><?php else: ?><?php foreach ($subcategories as $index => $sub): ?><tr class="<?php echo (int)($sub['is_active'] ?? 1) === 0 ? 'inactive-row' : ''; ?>"><td><?php echo $index + 1; ?></td><td><?php echo h($sub['category_name'] ?? '—'); ?></td><td><strong><?php echo h($sub['subcategory']); ?></strong><?php if ((int)($sub['is_active'] ?? 1) === 0): ?><span class="inactive-cross ms-2"><i class="bi bi-x-circle-fill"></i> Inactive</span><?php endif; ?><div class="small text-muted">Subcategory ID: <?php echo (int)$sub['id']; ?></div></td><td class="text-end fw-bold"><?php echo (int)($sub['linked_services'] ?? 0); ?></td><td><?php if ((int)($sub['is_active'] ?? 1) === 1): ?><span class="badge text-bg-success">Active</span><?php else: ?><span class="badge text-bg-danger"><i class="bi bi-x-circle me-1"></i>Inactive</span><?php endif; ?></td><td class="text-end"><div class="d-inline-flex gap-2 justify-content-end flex-wrap"><button type="button" class="btn btn-sm btn-outline-primary btn-edit-subcategory" data-bs-toggle="modal" data-bs-target="#subcategoryModal" data-id="<?php echo (int)$sub['id']; ?>" data-category-id="<?php echo (int)$sub['category_id']; ?>" data-subcategory="<?php echo h($sub['subcategory']); ?>"><i class="bi bi-pencil-square me-1"></i>Edit</button><button type="button" class="btn btn-sm btn-outline-danger btn-delete-subcategory" data-bs-toggle="modal" data-bs-target="#deleteSubcategoryModal" data-id="<?php echo (int)$sub['id']; ?>" data-subcategory="<?php echo h($sub['subcategory']); ?>" data-linked="<?php echo (int)($sub['linked_services'] ?? 0); ?>"><?php if ((int)($sub['linked_services'] ?? 0) > 0): ?><i class="bi bi-x-circle me-1"></i>Deactivate<?php else: ?><i class="bi bi-trash me-1"></i>Delete<?php endif; ?></button><?php if ((int)($sub['is_active'] ?? 1) === 0): ?><form method="post" class="d-inline"><input type="hidden" name="subcategory_id" value="<?php echo (int)$sub['id']; ?>"><button type="submit" name="reactivate_subcategory" value="1" class="btn btn-sm btn-outline-success"><i class="bi bi-check-circle me-1"></i>Reactivate</button></form><?php endif; ?></div></td></tr><?php endforeach; ?><?php endif; ?></tbody></table></div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button><button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#subcategoryModal" id="btnAddSubcategoryFromManage"><i class="bi bi-diagram-2 me-2"></i>Add Subcategory</button></div></div></div>
</div>

<!-- DELETE SUBCATEGORY MODAL -->
<div class="modal fade" id="deleteSubcategoryModal" tabindex="-1" aria-labelledby="deleteSubcategoryModalLabel" aria-hidden="true"><div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header"><h5 class="modal-title" id="deleteSubcategoryModalLabel">Delete Subcategory</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><input type="hidden" name="subcategory_id" id="delete_subcategory_id" value="0"><div class="alert alert-warning mb-0">Are you sure you want to remove <strong id="delete_subcategory_name"></strong>?<br><small id="delete_subcategory_help">If this subcategory is linked to services, it will be marked inactive instead of deleted.</small></div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" name="delete_subcategory" value="1" class="btn btn-danger" id="delete_subcategory_btn"><i class="bi bi-trash me-2"></i>Delete / Deactivate</button></div></form></div></div>

<!-- DELETE SERVICE MODAL -->
<div class="modal fade" id="deleteServiceModal" tabindex="-1" aria-labelledby="deleteServiceModalLabel" aria-hidden="true"><div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header"><h5 class="modal-title" id="deleteServiceModalLabel">Delete Service</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><input type="hidden" name="service_id" id="delete_service_id" value="0"><div class="alert alert-warning mb-0">Are you sure you want to remove <strong id="delete_service_name"></strong>?<br><small id="delete_service_help">If the service has already been used, it will be marked inactive instead of deleted.</small></div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" name="delete_service" value="1" class="btn btn-danger" id="delete_service_btn"><i class="bi bi-trash me-2"></i>Delete / Deactivate</button></div></form></div></div>

<!-- DELETE CATEGORY MODAL -->
<div class="modal fade" id="deleteCategoryModal" tabindex="-1" aria-labelledby="deleteCategoryModalLabel" aria-hidden="true"><div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header"><h5 class="modal-title" id="deleteCategoryModalLabel">Delete Category</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><input type="hidden" name="category_id" id="delete_category_id" value="0"><div class="alert alert-warning mb-0">Are you sure you want to remove <strong id="delete_category_name"></strong>?<br><small id="delete_category_help">If this category is linked to services, it will be marked inactive instead of deleted.</small></div></div><div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button><button type="submit" name="delete_category" value="1" class="btn btn-danger" id="delete_category_btn"><i class="bi bi-trash me-2"></i>Delete / Deactivate</button></div></form></div></div>

<div class="alert alert-info mt-3">
    <strong>Sale-side reminder:</strong> this setup records the linked fee services on <code>tblservices</code>. The extras posting/sale file must read <code>requires_related_fee</code>, <code>related_service_id_1</code>, and <code>related_service_id_2</code> and insert those linked services as additional extra lines when the main service is sold.
</div>

<style>
.hero-band{padding:14px 18px!important;margin-bottom:12px!important;border-radius:18px!important;}.hero-band .row{--bs-gutter-y:.75rem!important;}.hero-title{font-size:1.45rem!important;line-height:1.15!important;margin-top:.25rem!important;}.hero-subtitle{font-size:.85rem!important;line-height:1.25!important;margin-top:.25rem!important;max-width:720px;}.page-eyebrow{font-size:.72rem!important;letter-spacing:.06em!important;}.hero-band .btn{padding:.42rem .75rem!important;font-size:.84rem!important;border-radius:10px!important;}.row.g-4.mb-4{--bs-gutter-x:.75rem!important;--bs-gutter-y:.75rem!important;margin-bottom:.75rem!important;}.metric-card{padding:10px 12px!important;gap:10px!important;border-radius:16px!important;min-height:64px!important;}.metric-icon{width:34px!important;height:34px!important;border-radius:11px!important;font-size:14px!important;}.metric-label{font-size:.72rem!important;margin-bottom:1px!important;}.metric-value{font-size:1.05rem!important;line-height:1.1!important;}.panel-card{border-radius:18px!important;margin-bottom:.75rem!important;}.panel-card .card-header{padding:10px 14px!important;}.panel-card .card-body{padding:10px 12px!important;}.form-label{font-size:.74rem!important;margin-bottom:2px!important;font-weight:700!important;color:#475569!important;}.form-control,.form-select{height:34px!important;min-height:34px!important;padding:.32rem .55rem!important;font-size:.84rem!important;border-radius:10px!important;}.btn{border-radius:10px;}.card-header h5{font-size:.98rem!important;}.table-responsive{max-height:calc(100vh - 255px)!important;overflow:auto!important;border-radius:0 0 18px 18px!important;}.table-modern{font-size:.84rem!important;border-collapse:separate!important;border-spacing:0!important;}.table-modern thead th{position:sticky!important;top:0!important;z-index:20!important;background:linear-gradient(180deg,#ffffff,#f8fafc)!important;border-bottom:2px solid #e5e7eb!important;padding:8px 10px!important;font-size:.72rem!important;text-transform:uppercase!important;letter-spacing:.055em!important;white-space:nowrap!important;box-shadow:0 2px 0 rgba(15,23,42,.04)!important;}.table-modern tbody td{padding:7px 10px!important;vertical-align:middle!important;border-bottom:1px solid #edf2f7!important;}.table-modern tbody tr:hover{background:#f8fbff!important;}.data-stack strong{font-size:.84rem!important;line-height:1.15!important;}.data-stack small{font-size:.69rem!important;line-height:1.15!important;}.badge{font-size:.7rem!important;padding:.32em .55em!important;}.btn-sm{padding:.25rem .5rem!important;font-size:.76rem!important;}.modal .form-control,.modal .form-select{height:38px!important;}.manage-categories-table{max-height:420px!important;border-radius:0!important;}.inactive-row{background:#fff5f5!important;color:#9f1239!important;}.inactive-row strong{text-decoration:line-through;text-decoration-thickness:2px;text-decoration-color:#dc2626;}.inactive-cross{color:#dc2626!important;font-size:.72rem!important;font-weight:900!important;text-transform:uppercase;letter-spacing:.03em;}.select2-container{width:100%!important}.select2-container .select2-selection--single{height:38px!important;border:1px solid #d1d5db!important;border-radius:10px!important}.select2-container--default .select2-selection--single .select2-selection__rendered{line-height:36px!important;font-size:.84rem!important;color:#111827!important;padding-left:.55rem!important}.select2-container--default .select2-selection--single .select2-selection__arrow{height:36px!important}.select2-dropdown{border-radius:10px!important;border-color:#cbd5e1!important}.select2-search__field{outline:none!important}.select2-results__option{font-size:.84rem!important;padding:6px 10px!important}@media (max-width:991.98px){.table-responsive{max-height:calc(100vh - 300px)!important;}.hero-band{text-align:left!important;}}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var serviceModalLabel = document.getElementById('serviceModalLabel');
    var serviceId = document.getElementById('service_id');
    var serviceName = document.getElementById('service_name');
    var serviceCategory = document.getElementById('service_category');
    var serviceSubcategory = document.getElementById('service_subcategory');
    var servicePrice = document.getElementById('service_price');
    var requiresRelated = document.getElementById('requires_related_fee');
    var related1 = document.getElementById('related_service_id_1');
    var related2 = document.getElementById('related_service_id_2');
    var relatedBlocks = document.querySelectorAll('.related-fee-block');

    function initSearchSelects() {
        if (window.jQuery && jQuery.fn && jQuery.fn.select2) {
            jQuery('.service-search-select').select2({
                width: '100%',
                dropdownParent: jQuery('#serviceModal'),
                placeholder: 'Type to search service...',
                allowClear: false
            });
        }
    }

    function setSearchSelectValue(el, value) {
        if (!el) return;
        el.value = value || '0';
        if (window.jQuery && jQuery.fn && jQuery.fn.select2) {
            jQuery(el).val(value || '0').trigger('change.select2');
        }
    }

    /*
       Subcategory options are always filtered to match whichever category is
       currently selected, in both the Service modal and the list filter bar -
       a subcategory belongs to exactly one category, so showing unrelated
       ones would just be confusing (and could let a mismatched pair get saved).
    */
    function filterSubcategoryOptions(categorySelect, subcategorySelect, keepValueIfMatching) {
        if (!subcategorySelect) return;
        var categoryId = categorySelect ? (categorySelect.value || '') : '';
        var previousValue = subcategorySelect.value;
        var firstVisible = null;

        Array.prototype.forEach.call(subcategorySelect.options, function (opt) {
            if (!opt.value || opt.value === '0') { opt.hidden = false; return; }
            var optCategoryId = opt.getAttribute('data-category-id') || '';
            var show = !categoryId || optCategoryId === categoryId;
            opt.hidden = !show;
            if (show && firstVisible === null) firstVisible = opt.value;
        });

        if (keepValueIfMatching) {
            var stillValid = Array.prototype.some.call(subcategorySelect.options, function (opt) {
                return opt.value === previousValue && !opt.hidden;
            });
            if (!stillValid) subcategorySelect.value = '0';
        } else {
            subcategorySelect.value = '0';
        }
    }

    var categoryModalLabel = document.getElementById('categoryModalLabel');
    var categoryId = document.getElementById('category_id');
    var categoryName = document.getElementById('category_name');
    var categorySaveBtn = document.getElementById('categorySaveBtn');

    var subcategoryModalLabel = document.getElementById('subcategoryModalLabel');
    var subcategoryId = document.getElementById('subcategory_id');
    var subcategoryCategorySelect = document.getElementById('subcategory_category_id');
    var subcategoryName = document.getElementById('subcategory_name');
    var subcategorySaveBtn = document.getElementById('subcategorySaveBtn');

    function toggleRelatedBlocks() {
        var show = requiresRelated && requiresRelated.checked;
        relatedBlocks.forEach(function (el) { el.classList.toggle('d-none', !show); });
        if (!show) {
            setSearchSelectValue(related1, '0');
            setSearchSelectValue(related2, '0');
        }
    }

    function resetCategoryForm() {
        if (categoryModalLabel) categoryModalLabel.textContent = 'Add Service Category';
        if (categoryId) categoryId.value = '0';
        if (categoryName) categoryName.value = '';
        if (categorySaveBtn) categorySaveBtn.innerHTML = '<i class="bi bi-save me-2"></i>Save Category';
    }

    function editCategoryForm(id, name) {
        if (categoryModalLabel) categoryModalLabel.textContent = 'Edit Service Category';
        if (categoryId) categoryId.value = id || '0';
        if (categoryName) categoryName.value = name || '';
        if (categorySaveBtn) categorySaveBtn.innerHTML = '<i class="bi bi-save me-2"></i>Update Category';
    }

    function resetSubcategoryForm() {
        if (subcategoryModalLabel) subcategoryModalLabel.textContent = 'Add Subcategory';
        if (subcategoryId) subcategoryId.value = '0';
        if (subcategoryCategorySelect) subcategoryCategorySelect.value = '';
        if (subcategoryName) subcategoryName.value = '';
        if (subcategorySaveBtn) subcategorySaveBtn.innerHTML = '<i class="bi bi-save me-2"></i>Save Subcategory';
    }

    function editSubcategoryForm(id, categoryIdVal, name) {
        if (subcategoryModalLabel) subcategoryModalLabel.textContent = 'Edit Subcategory';
        if (subcategoryId) subcategoryId.value = id || '0';
        if (subcategoryCategorySelect) subcategoryCategorySelect.value = categoryIdVal || '';
        if (subcategoryName) subcategoryName.value = name || '';
        if (subcategorySaveBtn) subcategorySaveBtn.innerHTML = '<i class="bi bi-save me-2"></i>Update Subcategory';
    }

    function resetServiceForm() {
        if (serviceModalLabel) serviceModalLabel.textContent = 'Add Service';
        if (serviceId) serviceId.value = '0';
        if (serviceName) serviceName.value = '';
        if (serviceCategory) serviceCategory.value = '';
        filterSubcategoryOptions(serviceCategory, serviceSubcategory, false);
        if (servicePrice) servicePrice.value = '0.00';
        if (requiresRelated) requiresRelated.checked = false;
        setSearchSelectValue(related1, '0');
        setSearchSelectValue(related2, '0');
        toggleRelatedBlocks();
        clearSupplierRows();
    }

    /* ---------- Suppliers & Rates repeatable rows ---------- */
    var supplierRowsWrap = document.getElementById('supplierRows');
    var supplierTemplate = document.getElementById('supplierRowTemplate');
    var btnAddSupplierRow = document.getElementById('btnAddSupplierRow');

    function wireSupplierRow(rowEl) {
        // Give the cloned fields their real submit names.
        rowEl.querySelectorAll('[data-name]').forEach(function (el) {
            el.setAttribute('name', el.getAttribute('data-name') + '[]');
            el.removeAttribute('data-name');
        });
        var removeBtn = rowEl.querySelector('.btn-remove-supplier-row');
        if (removeBtn) removeBtn.addEventListener('click', function () { rowEl.remove(); });
    }

    function addSupplierRow(supplierId, rate) {
        if (!supplierRowsWrap || !supplierTemplate) return;
        var frag = supplierTemplate.content.cloneNode(true);
        var rowEl = frag.querySelector('.supplier-row');
        wireSupplierRow(rowEl);
        supplierRowsWrap.appendChild(rowEl);
        if (typeof supplierId !== 'undefined' && supplierId !== null) {
            var sel = rowEl.querySelector('.supplier-select');
            if (sel) sel.value = String(supplierId);
        }
        if (typeof rate !== 'undefined' && rate !== null) {
            var rateInput = rowEl.querySelector('.supplier-rate');
            if (rateInput) rateInput.value = parseFloat(rate).toFixed(2);
        }
    }

    function clearSupplierRows() {
        if (supplierRowsWrap) supplierRowsWrap.innerHTML = '';
    }

    function loadSupplierRows(json) {
        clearSupplierRows();
        if (!json) return;
        var list = [];
        try { list = JSON.parse(json); } catch (e) { list = []; }
        if (!Array.isArray(list)) return;
        list.forEach(function (item) {
            addSupplierRow(item.supplier_id, item.rate);
        });
    }

    if (btnAddSupplierRow) btnAddSupplierRow.addEventListener('click', function () { addSupplierRow(); });

    document.querySelectorAll('#btnNewService, #btnNewServiceTop').forEach(function (btn) { btn.addEventListener('click', resetServiceForm); });

    document.querySelectorAll('.btn-edit-service').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (serviceModalLabel) serviceModalLabel.textContent = 'Edit Service';
            if (serviceId) serviceId.value = this.getAttribute('data-id') || '0';
            if (serviceName) serviceName.value = this.getAttribute('data-service') || '';
            if (serviceCategory) serviceCategory.value = this.getAttribute('data-category') || '';
            filterSubcategoryOptions(serviceCategory, serviceSubcategory, true);
            if (serviceSubcategory) serviceSubcategory.value = this.getAttribute('data-subcategory') || '0';
            if (servicePrice) servicePrice.value = this.getAttribute('data-price') || '0.00';
            if (requiresRelated) requiresRelated.checked = (this.getAttribute('data-requires-related') || '0') === '1';
            setSearchSelectValue(related1, this.getAttribute('data-related1') || '0');
            setSearchSelectValue(related2, this.getAttribute('data-related2') || '0');
            toggleRelatedBlocks();
            loadSupplierRows(this.getAttribute('data-suppliers') || '');
        });
    });

    if (serviceCategory) serviceCategory.addEventListener('change', function () { filterSubcategoryOptions(serviceCategory, serviceSubcategory, false); });
    if (requiresRelated) requiresRelated.addEventListener('change', toggleRelatedBlocks);

    document.querySelectorAll('#btnNewCategory, #btnAddCategoryFromManage').forEach(function (btn) { btn.addEventListener('click', resetCategoryForm); });
    document.querySelectorAll('.btn-edit-category').forEach(function (btn) { btn.addEventListener('click', function () { editCategoryForm(this.getAttribute('data-id') || '0', this.getAttribute('data-category') || ''); }); });

    document.querySelectorAll('#btnNewSubcategory, #btnAddSubcategoryFromManage').forEach(function (btn) { btn.addEventListener('click', resetSubcategoryForm); });
    document.querySelectorAll('.btn-edit-subcategory').forEach(function (btn) {
        btn.addEventListener('click', function () {
            editSubcategoryForm(this.getAttribute('data-id') || '0', this.getAttribute('data-category-id') || '', this.getAttribute('data-subcategory') || '');
        });
    });

    var filterCategory = document.getElementById('filter_category');
    var filterSubcategory = document.getElementById('filter_subcategory');
    if (filterCategory && filterSubcategory) {
        filterSubcategoryOptions(filterCategory, filterSubcategory, true);
        filterCategory.addEventListener('change', function () { filterSubcategoryOptions(filterCategory, filterSubcategory, false); });
    }

    var deleteId = document.getElementById('delete_service_id');
    var deleteName = document.getElementById('delete_service_name');
    var deleteHelp = document.getElementById('delete_service_help');
    var deleteBtn = document.getElementById('delete_service_btn');
    document.querySelectorAll('.btn-delete-service').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var used = parseInt(this.getAttribute('data-used') || '0', 10) || 0;
            if (deleteId) deleteId.value = this.getAttribute('data-id') || '0';
            if (deleteName) deleteName.textContent = this.getAttribute('data-service') || '';
            if (deleteHelp) deleteHelp.textContent = used > 0 ? 'This service has already been used, so it will be marked inactive and shown with a red cross.' : 'This service has not been used, so it can be permanently deleted.';
            if (deleteBtn) deleteBtn.innerHTML = used > 0 ? '<i class="bi bi-x-circle me-2"></i>Mark Inactive' : '<i class="bi bi-trash me-2"></i>Delete Service';
        });
    });

    var deleteCategoryId = document.getElementById('delete_category_id');
    var deleteCategoryName = document.getElementById('delete_category_name');
    var deleteCategoryHelp = document.getElementById('delete_category_help');
    var deleteCategoryBtn = document.getElementById('delete_category_btn');
    document.querySelectorAll('.btn-delete-category').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var linked = parseInt(this.getAttribute('data-linked') || '0', 10) || 0;
            if (deleteCategoryId) deleteCategoryId.value = this.getAttribute('data-id') || '0';
            if (deleteCategoryName) deleteCategoryName.textContent = this.getAttribute('data-category') || '';
            if (deleteCategoryHelp) deleteCategoryHelp.textContent = linked > 0 ? 'This category is linked to ' + linked + ' service(s), so it will be marked inactive and shown with a red cross.' : 'This category is not linked to any service, so it can be permanently deleted.';
            if (deleteCategoryBtn) deleteCategoryBtn.innerHTML = linked > 0 ? '<i class="bi bi-x-circle me-2"></i>Mark Inactive' : '<i class="bi bi-trash me-2"></i>Delete Category';
        });
    });

    var deleteSubcategoryId = document.getElementById('delete_subcategory_id');
    var deleteSubcategoryName = document.getElementById('delete_subcategory_name');
    var deleteSubcategoryHelp = document.getElementById('delete_subcategory_help');
    var deleteSubcategoryBtn = document.getElementById('delete_subcategory_btn');
    document.querySelectorAll('.btn-delete-subcategory').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var linked = parseInt(this.getAttribute('data-linked') || '0', 10) || 0;
            if (deleteSubcategoryId) deleteSubcategoryId.value = this.getAttribute('data-id') || '0';
            if (deleteSubcategoryName) deleteSubcategoryName.textContent = this.getAttribute('data-subcategory') || '';
            if (deleteSubcategoryHelp) deleteSubcategoryHelp.textContent = linked > 0 ? 'This subcategory is linked to ' + linked + ' service(s), so it will be marked inactive and shown with a red cross.' : 'This subcategory is not linked to any service, so it can be permanently deleted.';
            if (deleteSubcategoryBtn) deleteSubcategoryBtn.innerHTML = linked > 0 ? '<i class="bi bi-x-circle me-2"></i>Mark Inactive' : '<i class="bi bi-trash me-2"></i>Delete Subcategory';
        });
    });

    initSearchSelects();
    toggleRelatedBlocks();
    filterSubcategoryOptions(serviceCategory, serviceSubcategory, true);
});
</script>

<?php endif; ?>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
