
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/*
|--------------------------------------------------------------------------
| PURE CHEMICAL - SERVICE MANAGER
|--------------------------------------------------------------------------
| File: admin/add_service.php
| Tables: services, media
| Features: Add, Edit, Delete, Image Upload, Search
|--------------------------------------------------------------------------
*/

$baseDir = dirname(__DIR__);
$dbFile  = __DIR__ . '/includes/db.php';

if (!is_file($dbFile)) {
    $dbFile = $baseDir . '/includes/db.php';
}

if (!is_file($dbFile)) {
    die('Database file not found. Please check admin/includes/db.php.');
}

require_once $dbFile;

/*
 * Authentication: agar project mein auth.php hai to usi ka use hoga.
 */
$authFile = __DIR__ . '/includes/auth.php';

if (is_file($authFile)) {
    require_once $authFile;

    if (function_exists('requireAdmin')) {
        requireAdmin();
    }
}

/*
 * Database connection check
 */
if (!isset($pdo) || !($pdo instanceof PDO)) {
    die('Database connection $pdo nahi mila. includes/db.php check karein.');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| HELPERS
|--------------------------------------------------------------------------
*/

function svc_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function svc_csrf(): string
{
    if (empty($_SESSION['svc_csrf_token'])) {
        $_SESSION['svc_csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['svc_csrf_token'];
}

function svc_flash(string $type, string $message): void
{
    $_SESSION['svc_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function svc_redirect(): void
{
    header('Location: add_service.php');
    exit;
}

function svc_slug(string $text): string
{
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    $text = trim((string)$text, '-');

    return $text !== '' ? $text : 'service';
}

function svc_unique_slug(
    PDO $pdo,
    string $slug,
    int $excludeId = 0
): string {
    $base = $slug;
    $counter = 2;

    while (true) {
        $sql = 'SELECT id FROM services WHERE slug = :slug';
        $params = [':slug' => $slug];

        if ($excludeId > 0) {
            $sql .= ' AND id != :exclude_id';
            $params[':exclude_id'] = $excludeId;
        }

        $sql .= ' LIMIT 1';

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        if (!$stmt->fetch()) {
            return $slug;
        }

        $slug = $base . '-' . $counter;
        $counter++;
    }
}

function svc_upload_image(PDO $pdo, string $field, array &$createdFiles): ?int
{
    if (
        !isset($_FILES[$field]) ||
        !is_array($_FILES[$field]) ||
        ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
    ) {
        return null;
    }

    $file = $_FILES[$field];
    $error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);

    if ($error !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Image upload nahi hui. Error code: ' . $error);
    }

    $tmp  = (string)($file['tmp_name'] ?? '');
    $size = (int)($file['size'] ?? 0);

    if (!is_uploaded_file($tmp)) {
        throw new RuntimeException('Invalid uploaded image.');
    }

    if ($size <= 0 || $size > 5 * 1024 * 1024) {
        throw new RuntimeException('Image ka size 5 MB se kam hona chahiye.');
    }

    $imageInfo = @getimagesize($tmp);

    if ($imageInfo === false) {
        throw new RuntimeException('Uploaded file valid image nahi hai.');
    }

    $mimeMap = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
        'image/gif'  => 'gif',
    ];

    $mime = $imageInfo['mime'] ?? '';

    if (!isset($mimeMap[$mime])) {
        throw new RuntimeException('Sirf JPG, PNG, WEBP aur GIF allowed hain.');
    }

    $extension = $mimeMap[$mime];

    $uploadDir = dirname(__DIR__) . '/uploads/services';

    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
            throw new RuntimeException('uploads/services folder create nahi hua.');
        }
    }

    if (!is_writable($uploadDir)) {
        throw new RuntimeException('uploads/services folder writable nahi hai.');
    }

    $newName = bin2hex(random_bytes(16)) . '.' . $extension;
    $absolutePath = $uploadDir . '/' . $newName;
    $relativePath = 'uploads/services/' . $newName;

    if (!move_uploaded_file($tmp, $absolutePath)) {
        throw new RuntimeException('Image server par save nahi ho saki.');
    }

    $createdFiles[] = $absolutePath;

    /*
     * uploaded_by NULL rakha hai, taaki users table ki
     * foreign-key constraint se invalid user ID error na aaye.
     */
    $stmt = $pdo->prepare(
        "INSERT INTO media
        (
            folder_id,
            original_name,
            file_name,
            file_path,
            mime_type,
            file_type,
            extension,
            file_size,
            width,
            height,
            alt_text,
            title,
            uploaded_by,
            status
        )
        VALUES
        (
            NULL,
            :original_name,
            :file_name,
            :file_path,
            :mime_type,
            'image',
            :extension,
            :file_size,
            :width,
            :height,
            :alt_text,
            :title,
            NULL,
            1
        )"
    );

    $originalName = basename((string)($file['name'] ?? 'image'));

    $stmt->execute([
        ':original_name' => substr($originalName, 0, 255),
        ':file_name'     => $newName,
        ':file_path'     => $relativePath,
        ':mime_type'     => $mime,
        ':extension'     => $extension,
        ':file_size'     => $size,
        ':width'         => (int)$imageInfo[0],
        ':height'        => (int)$imageInfo[1],
        ':alt_text'      => substr(pathinfo($originalName, PATHINFO_FILENAME), 0, 255),
        ':title'         => substr(pathinfo($originalName, PATHINFO_FILENAME), 0, 255),
    ]);

    return (int)$pdo->lastInsertId();
}

function svc_image_url(?string $path): string
{
    $path = trim((string)$path);

    if ($path === '') {
        return '';
    }

    /*
     * Database ke relative file paths ke liye.
     */
    if (
        preg_match('~^https?://~i', $path) ||
        str_starts_with($path, 'data:')
    ) {
        return $path;
    }

    return '../' . ltrim($path, '/');
}

/*
|--------------------------------------------------------------------------
| POST ACTIONS
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = (string)($_POST['csrf_token'] ?? '');
    $savedToken = (string)($_SESSION['svc_csrf_token'] ?? '');

    if (
        $savedToken === '' ||
        $token === '' ||
        !hash_equals($savedToken, $token)
    ) {
        svc_flash('error', 'Security token expire ho gaya. Dobara try karein.');
        svc_redirect();
    }

    $action = (string)($_POST['action'] ?? '');
    $createdFiles = [];
    $transactionStarted = false;

    try {
        /*
        |------------------------------------------------------------------
        | DELETE SERVICE
        |------------------------------------------------------------------
        */
        if ($action === 'delete') {
            $id = filter_var(
                $_POST['id'] ?? null,
                FILTER_VALIDATE_INT,
                ['options' => ['min_range' => 1]]
            );

            if (!$id) {
                throw new RuntimeException('Invalid service ID.');
            }

            $stmt = $pdo->prepare('SELECT id FROM services WHERE id = ?');
            $stmt->execute([(int)$id]);

            if (!$stmt->fetch()) {
                throw new RuntimeException('Service nahi mili ya pehle delete ho chuki hai.');
            }

            /*
             * Parent service ko delete karne se pehle uske child records
             * ko orphan hone se bachaya jata hai.
             */
            $stmt = $pdo->prepare(
                'SELECT COUNT(*) FROM services WHERE parent_id = ?'
            );
            $stmt->execute([(int)$id]);

            if ((int)$stmt->fetchColumn() > 0) {
                throw new RuntimeException(
                    'Is service ki child services hain. Pehle unka parent badlein ya unhe delete karein.'
                );
            }

            $stmt = $pdo->prepare('DELETE FROM services WHERE id = ?');
            $stmt->execute([(int)$id]);

            svc_flash('success', 'Service successfully delete ho gayi.');
            svc_redirect();
        }

        /*
        |------------------------------------------------------------------
        | SAVE / UPDATE SERVICE
        |------------------------------------------------------------------
        */
        if ($action !== 'save') {
            throw new RuntimeException('Invalid action.');
        }

        $id = (int)($_POST['id'] ?? 0);
        $name = trim((string)($_POST['name'] ?? ''));
        $slugInput = trim((string)($_POST['slug'] ?? ''));
        $shortDescription = trim((string)($_POST['short_description'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $icon = trim((string)($_POST['icon'] ?? ''));
        $parentId = (int)($_POST['parent_id'] ?? 0);
        $status = isset($_POST['status']) ? 1 : 0;
        $featured = isset($_POST['featured']) ? 1 : 0;
        $sortOrder = (int)($_POST['sort_order'] ?? 0);

        if ($name === '') {
            throw new RuntimeException('Service name required hai.');
        }

        if (mb_strlen($name) > 255) {
            throw new RuntimeException('Service name 255 characters se chhota rakhein.');
        }

        if (mb_strlen($icon) > 150) {
            throw new RuntimeException('Icon field 150 characters se chhota rakhein.');
        }

        if (mb_strlen($shortDescription) > 65535) {
            throw new RuntimeException('Short description bahut lamba hai.');
        }

        if ($id > 0) {
            $stmt = $pdo->prepare('SELECT id FROM services WHERE id = ?');
            $stmt->execute([$id]);

            if (!$stmt->fetch()) {
                throw new RuntimeException('Edit karne wali service nahi mili.');
            }
        }

        if ($parentId > 0) {
            if ($parentId === $id) {
                throw new RuntimeException('Service apni khud ki parent nahi ho sakti.');
            }

            $stmt = $pdo->prepare('SELECT id FROM services WHERE id = ?');
            $stmt->execute([$parentId]);

            if (!$stmt->fetch()) {
                throw new RuntimeException('Selected parent service maujood nahi hai.');
            }

            /*
             * Ancestor chain check: cycle create hone se bachata hai.
             */
            $ancestor = $parentId;
            $visited = [];

            while ($ancestor > 0) {
                if ($ancestor === $id) {
                    throw new RuntimeException(
                        'Invalid parent selection: circular hierarchy allowed nahi hai.'
                    );
                }

                if (isset($visited[$ancestor])) {
                    throw new RuntimeException('Existing service hierarchy mein circular link mila.');
                }

                $visited[$ancestor] = true;

                $stmt = $pdo->prepare(
                    'SELECT parent_id FROM services WHERE id = ?'
                );
                $stmt->execute([$ancestor]);
                $row = $stmt->fetch();

                if (!$row || $row['parent_id'] === null) {
                    break;
                }

                $ancestor = (int)$row['parent_id'];
            }
        }

        $slug = svc_unique_slug(
            $pdo,
            svc_slug($slugInput !== '' ? $slugInput : $name),
            $id
        );

        $pdo->beginTransaction();
        $transactionStarted = true;

        /*
         * Nayi image upload ho to uski media ID milegi.
         * Nahi ho to purani image ID retain hogi.
         */
        $featuredUploadId = svc_upload_image(
            $pdo,
            'featured_image',
            $createdFiles
        );

        $bannerUploadId = svc_upload_image(
            $pdo,
            'banner_image',
            $createdFiles
        );

        if ($id > 0) {
            $stmt = $pdo->prepare(
                'SELECT featured_image_id, banner_id
                 FROM services
                 WHERE id = ?'
            );
            $stmt->execute([$id]);
            $old = $stmt->fetch();

            if (!$old) {
                throw new RuntimeException('Service record nahi mila.');
            }

            $featuredImageId = $featuredUploadId
                ?? ($old['featured_image_id'] !== null
                    ? (int)$old['featured_image_id'] : null);

            $bannerId = $bannerUploadId
                ?? ($old['banner_id'] !== null
                    ? (int)$old['banner_id'] : null);

            $stmt = $pdo->prepare(
                'UPDATE services SET
                    parent_id = :parent_id,
                    name = :name,
                    slug = :slug,
                    short_description = :short_description,
                    description = :description,
                    icon = :icon,
                    featured_image_id = :featured_image_id,
                    banner_id = :banner_id,
                    status = :status,
                    featured = :featured,
                    sort_order = :sort_order
                 WHERE id = :id'
            );

            $stmt->execute([
                ':parent_id'          => $parentId > 0 ? $parentId : null,
                ':name'               => $name,
                ':slug'               => $slug,
                ':short_description'  => $shortDescription !== '' ? $shortDescription : null,
                ':description'        => $description !== '' ? $description : null,
                ':icon'               => $icon !== '' ? $icon : null,
                ':featured_image_id'  => $featuredImageId,
                ':banner_id'          => $bannerId,
                ':status'             => $status,
                ':featured'           => $featured,
                ':sort_order'         => $sortOrder,
                ':id'                 => $id,
            ]);

            $successMessage = 'Service successfully update ho gayi.';
        } else {
            $stmt = $pdo->prepare(
                'INSERT INTO services (
                    parent_id,
                    name,
                    slug,
                    short_description,
                    description,
                    icon,
                    featured_image_id,
                    banner_id,
                    status,
                    featured,
                    sort_order
                ) VALUES (
                    :parent_id,
                    :name,
                    :slug,
                    :short_description,
                    :description,
                    :icon,
                    :featured_image_id,
                    :banner_id,
                    :status,
                    :featured,
                    :sort_order
                )'
            );

            $stmt->execute([
                ':parent_id'          => $parentId > 0 ? $parentId : null,
                ':name'               => $name,
                ':slug'               => $slug,
                ':short_description'  => $shortDescription !== '' ? $shortDescription : null,
                ':description'        => $description !== '' ? $description : null,
                ':icon'               => $icon !== '' ? $icon : null,
                ':featured_image_id'  => $featuredUploadId,
                ':banner_id'          => $bannerUploadId,
                ':status'             => $status,
                ':featured'           => $featured,
                ':sort_order'         => $sortOrder,
            ]);

            $successMessage = 'New service successfully add ho gayi.';
        }

        $pdo->commit();
        $transactionStarted = false;

        svc_flash('success', $successMessage);
        svc_redirect();

    } catch (Throwable $ex) {
        if ($transactionStarted && $pdo->inTransaction()) {
            $pdo->rollBack();
        }

        /*
         * Transaction fail hone par current request ki files hata do.
         * Database transaction ke andar bani media entries rollback ho jayengi.
         */
        foreach ($createdFiles as $createdFile) {
            if (is_file($createdFile)) {
                @unlink($createdFile);
            }
        }

        error_log('Pure Chemical Service Manager: ' . $ex->getMessage());

        /*
         * Development mein useful database message show hoga.
         * Production par detailed errors ko log mein hi rakhein.
         */
        svc_flash('error', $ex->getMessage());
        svc_redirect();
    }
}

/*
|--------------------------------------------------------------------------
| PAGE DATA
|--------------------------------------------------------------------------
*/

$flash = $_SESSION['svc_flash'] ?? null;
unset($_SESSION['svc_flash']);

$editId = (int)($_GET['edit'] ?? 0);
$editing = null;

if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM services WHERE id = ?');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch();

    if (!$editing) {
        $flash = [
            'type' => 'error',
            'message' => 'Edit karne wali service nahi mili.'
        ];
    }
}

$services = $pdo->query(
    'SELECT
        s.*,
        p.name AS parent_name,
        fm.file_path AS featured_image_path,
        bm.file_path AS banner_image_path
     FROM services s
     LEFT JOIN services p ON p.id = s.parent_id
     LEFT JOIN media fm ON fm.id = s.featured_image_id
     LEFT JOIN media bm ON bm.id = s.banner_id
     ORDER BY s.sort_order ASC, s.id DESC'
)->fetchAll();

$parentServices = $pdo->query(
    'SELECT id, name FROM services ORDER BY name ASC'
)->fetchAll();

$totalServices = count($services);
$activeServices = 0;
$featuredServices = 0;

foreach ($services as $serviceRow) {
    if ((int)$serviceRow['status'] === 1) {
        $activeServices++;
    }

    if ((int)$serviceRow['featured'] === 1) {
        $featuredServices++;
    }
}

$editingFeaturedPath = '';
$editingBannerPath = '';

if ($editing) {
    if (!empty($editing['featured_image_id'])) {
        $stmt = $pdo->prepare('SELECT file_path FROM media WHERE id = ?');
        $stmt->execute([(int)$editing['featured_image_id']]);
        $editingFeaturedPath = (string)($stmt->fetchColumn() ?: '');
    }

    if (!empty($editing['banner_id'])) {
        $stmt = $pdo->prepare('SELECT file_path FROM media WHERE id = ?');
        $stmt->execute([(int)$editing['banner_id']]);
        $editingBannerPath = (string)($stmt->fetchColumn() ?: '');
    }
}

$editingId = (int)($editing['id'] ?? 0);
$csrfToken = svc_csrf();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Service Manager | Pure Chemical Admin</title>

<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: #2563eb;
    --primary-dark: #1d4ed8;
    --ink: #172033;
    --muted: #68758a;
    --line: #e6ebf2;
    --surface: #ffffff;
    --page: #f4f7fb;
    --success: #15803d;
    --danger: #dc2626;
    --radius: 18px;
    --shadow: 0 8px 28px rgba(25, 42, 70, .055);
}
* { box-sizing: border-box; }
body {
    margin: 0;
    background: var(--page);
    color: var(--ink);
    font-family: Inter, Arial, sans-serif;
}
input, textarea, select, button { font: inherit; }
.svc-page {
    margin-left: 260px;
    padding: 30px;
    min-height: 100vh;
}
.svc-container { max-width: 1600px; margin: auto; }
.svc-topbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 18px;
    margin-bottom: 26px;
}
.svc-eyebrow {
    font-size: 11px;
    letter-spacing: 1.8px;
    font-weight: 800;
    color: var(--primary);
    text-transform: uppercase;
    margin-bottom: 9px;
}
.svc-topbar h1 {
    margin: 0;
    font-size: clamp(25px, 3vw, 34px);
    letter-spacing: -1.2px;
    font-weight: 800;
}
.svc-subtitle { color: var(--muted); font-size: 13px; margin-top: 9px; }
.svc-btn {
    border: 1px solid var(--line);
    background: #fff;
    color: var(--ink);
    border-radius: 11px;
    padding: 11px 15px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-weight: 700;
    font-size: 12px;
    text-decoration: none;
    cursor: pointer;
    transition: .2s ease;
}
.svc-btn:hover { transform: translateY(-1px); box-shadow: var(--shadow); }
.svc-btn-primary {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}
.svc-btn-primary:hover { background: var(--primary-dark); }
.svc-btn-danger { color: var(--danger); border-color: #fecaca; background: #fff; }
.svc-btn-soft { background: #eef4ff; border-color: #dce8ff; color: var(--primary); }
.svc-stats {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 16px;
    margin-bottom: 22px;
}
.svc-stat, .svc-card {
    background: var(--surface);
    border: 1px solid var(--line);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
}
.svc-stat {
    padding: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
    min-width: 0;
}
.svc-stat-icon {
    width: 46px; height: 46px; border-radius: 14px;
    display: grid; place-items: center; background: #eef4ff;
    color: var(--primary); flex-shrink: 0;
}
.svc-stat:nth-child(2) .svc-stat-icon { background: #eaf9ef; color: var(--success); }
.svc-stat:nth-child(3) .svc-stat-icon { background: #fff5e7; color: #b76b00; }
.svc-stat small { color: var(--muted); font-size: 12px; font-weight: 600; }
.svc-stat strong { display: block; font-size: 27px; margin-top: 6px; }
.svc-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.05fr) minmax(300px, .95fr);
    gap: 20px;
    align-items: start;
}
.svc-card { overflow: hidden; min-width: 0; }
.svc-card-head {
    padding: 21px 23px;
    border-bottom: 1px solid var(--line);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
}
.svc-card-head h2 { margin: 0; font-size: 16px; font-weight: 800; }
.svc-card-head p { margin: 6px 0 0; color: var(--muted); font-size: 12px; }
.svc-card-body { padding: 23px; }
.svc-field { margin-bottom: 18px; min-width: 0; }
.svc-field label {
    display: block; margin-bottom: 8px; font-size: 12px;
    font-weight: 700; color: #344157;
}
.svc-field label span { color: var(--danger); }
.svc-input, .svc-select, .svc-textarea {
    width: 100%; max-width: 100%; min-width: 0;
    padding: 12px 13px; border: 1px solid #dce3ed;
    border-radius: 11px; background: #fff; color: var(--ink);
    outline: none; font-size: 13px; transition: .2s;
}
.svc-input:focus, .svc-select:focus, .svc-textarea:focus {
    border-color: #8db4ff; box-shadow: 0 0 0 4px #2563eb12;
}
.svc-textarea { min-height: 105px; resize: vertical; line-height: 1.6; }
.svc-help { display: block; margin-top: 7px; color: var(--muted); font-size: 11px; line-height: 1.5; }
.svc-two-col { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.svc-toggle-row { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 19px; }
.svc-toggle {
    display: flex; align-items: center; gap: 9px; padding: 11px 12px;
    border: 1px solid var(--line); border-radius: 11px;
    color: #39465c; font-size: 12px; font-weight: 700; flex: 1;
}
.svc-toggle input { accent-color: var(--primary); width: 16px; height: 16px; }
.svc-upload {
    position: relative; border: 1px dashed #c8d4e5; border-radius: 13px;
    background: #f9fbfe; padding: 15px; min-width: 0;
}
.svc-upload input { width: 100%; max-width: 100%; font-size: 11px; }
.svc-upload-preview {
    display: none; margin-top: 12px; max-width: 100%;
    width: 100%; max-height: 160px; object-fit: cover; border-radius: 10px;
}
.svc-existing-image {
    width: 100%; max-height: 135px; object-fit: cover;
    border-radius: 10px; margin-bottom: 10px;
}
.svc-form-actions {
    display: flex; flex-wrap: wrap; gap: 10px;
    border-top: 1px solid var(--line); padding-top: 19px; margin-top: 8px;
}
.svc-flash {
    padding: 14px 16px; border-radius: 12px; margin-bottom: 20px;
    font-size: 13px; font-weight: 600; line-height: 1.6;
}
.svc-flash.success { background: #eaf9ef; color: #166534; border: 1px solid #c9efd5; }
.svc-flash.error { background: #fff0f0; color: #991b1b; border: 1px solid #fecaca; }
.svc-list-toolbar {
    padding: 18px 20px; border-bottom: 1px solid var(--line);
    display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
}
.svc-search-wrap { flex: 1; min-width: 150px; position: relative; }
.svc-search-wrap i { position: absolute; left: 13px; top: 13px; color: #8592a7; font-size: 12px; }
.svc-search { padding-left: 35px; }
.svc-table-wrap { width: 100%; overflow-x: auto; }
.svc-table { width: 100%; border-collapse: collapse; min-width: 620px; }
.svc-table th {
    padding: 13px 17px; text-align: left; font-size: 10px;
    color: #778399; text-transform: uppercase; letter-spacing: .8px;
    background: #fafbfd; white-space: nowrap;
}
.svc-table td {
    padding: 14px 17px; border-top: 1px solid #edf0f5;
    vertical-align: middle; font-size: 12px;
}
.svc-table tbody tr:hover { background: #fbfcff; }
.svc-service-name { display: flex; align-items: center; gap: 11px; min-width: 200px; }
.svc-thumb {
    width: 43px; height: 43px; flex-shrink: 0; border-radius: 11px;
    background: #eef4ff; display: grid; place-items: center;
    color: var(--primary); overflow: hidden;
}
.svc-thumb img { width: 100%; height: 100%; object-fit: cover; }
.svc-name { font-weight: 800; font-size: 12px; overflow-wrap: anywhere; }
.svc-slug { color: #8590a2; font-size: 10px; margin-top: 5px; overflow-wrap: anywhere; }
.svc-pill {
    display: inline-flex; align-items: center; gap: 5px;
    border-radius: 50px; padding: 6px 9px; font-size: 10px; font-weight: 800;
    white-space: nowrap;
}
.svc-pill.active { background: #e9f9ef; color: #16803d; }
.svc-pill.inactive { background: #f1f3f7; color: #697386; }
.svc-pill.featured { background: #fff5dc; color: #966000; }
.svc-row-actions { display: flex; align-items: center; gap: 7px; }
.svc-icon-btn {
    width: 33px; height: 33px; display: grid; place-items: center;
    border: 1px solid var(--line); border-radius: 9px; color: #506079;
    background: white; text-decoration: none; cursor: pointer;
}
.svc-icon-btn:hover { color: var(--primary); background: #eef4ff; }
.svc-icon-btn.delete:hover { color: var(--danger); background: #fff0f0; }
.svc-empty { padding: 42px 20px; text-align: center; color: var(--muted); }
.svc-empty i { font-size: 30px; margin-bottom: 12px; color: #b6c5dc; }
.svc-empty strong { display: block; color: var(--ink); margin-bottom: 7px; }
.svc-note {
    background: #f7f9fd; border: 1px solid var(--line);
    border-radius: 12px; padding: 13px; font-size: 11px;
    color: var(--muted); line-height: 1.7; margin-bottom: 20px;
}
.svc-danger-zone {
    border: 1px solid #fecaca; border-radius: 13px;
    padding: 15px; background: #fffafa; margin-top: 20px;
}
.svc-danger-zone h3 { margin: 0 0 7px; font-size: 13px; color: #991b1b; }
.svc-danger-zone p { margin: 0 0 12px; font-size: 11px; line-height: 1.6; color: #8d5a5a; }
.svc-hidden { display: none !important; }
@media (max-width: 1200px) {
    .svc-page { padding: 22px; }
    .svc-grid { grid-template-columns: 1fr; }
}
@media (max-width: 850px) {
    .svc-page { margin-left: 0; padding: 16px; }
    .svc-topbar { align-items: flex-start; flex-direction: column; }
    .svc-stats { gap: 10px; }
    .svc-stat { padding: 13px; gap: 9px; }
    .svc-stat-icon { width: 37px; height: 37px; }
    .svc-stat strong { font-size: 22px; }
    .svc-stat small { font-size: 10px; }
}
@media (max-width: 520px) {
    .svc-stats { grid-template-columns: 1fr; }
    .svc-two-col { grid-template-columns: 1fr; gap: 0; }
    .svc-card-head, .svc-card-body { padding: 17px; }
    .svc-form-actions .svc-btn { flex: 1; }
}
</style>
</head>

<body>

<?php
$sidebarFile = __DIR__ . '/sidebar.php';
if (is_file($sidebarFile)) {
    require $sidebarFile;
}
?>

<main class="svc-page">
<div class="svc-container">

    <header class="svc-topbar">
        <div>
            <div class="svc-eyebrow">Pure Chemical / Content Management</div>
            <h1>Service Manager</h1>
            <div class="svc-subtitle">Create, manage and organize your website services.</div>
        </div>

        <a href="add_service.php" class="svc-btn svc-btn-primary">
            <i class="fa-solid fa-plus"></i> New Service
        </a>
    </header>

    <?php if (is_array($flash) && !empty($flash['message'])): ?>
        <div class="svc-flash <?= ($flash['type'] ?? '') === 'success' ? 'success' : 'error' ?>">
            <i class="fa-solid <?= ($flash['type'] ?? '') === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation' ?>"></i>
            <?= svc_e($flash['message']) ?>
        </div>
    <?php endif; ?>

    <section class="svc-stats">
        <div class="svc-stat">
            <div class="svc-stat-icon"><i class="fa-solid fa-layer-group"></i></div>
            <div><small>Total Services</small><strong><?= $totalServices ?></strong></div>
        </div>
        <div class="svc-stat">
            <div class="svc-stat-icon"><i class="fa-solid fa-circle-check"></i></div>
            <div><small>Active Services</small><strong><?= $activeServices ?></strong></div>
        </div>
        <div class="svc-stat">
            <div class="svc-stat-icon"><i class="fa-solid fa-star"></i></div>
            <div><small>Featured Services</small><strong><?= $featuredServices ?></strong></div>
        </div>
    </section>

    <section class="svc-grid">

        <!-- ADD / EDIT FORM -->
        <div class="svc-card" id="service-editor">
            <div class="svc-card-head">
                <div>
                    <h2>
                        <i class="fa-solid <?= $editing ? 'fa-pen-to-square' : 'fa-circle-plus' ?>"></i>
                        <?= $editing ? 'Edit Service' : 'Create New Service' ?>
                    </h2>
                    <p><?= $editing ? 'Update service details below.' : 'Add a service to your website.' ?></p>
                </div>

                <?php if ($editing): ?>
                    <a class="svc-btn svc-btn-soft" href="add_service.php">
                        <i class="fa-solid fa-xmark"></i> Cancel
                    </a>
                <?php endif; ?>
            </div>

            <div class="svc-card-body">
                <div class="svc-note">
                    <i class="fa-solid fa-circle-info"></i>
                    Required fields are marked with <strong>*</strong>.
                    Images are stored in the media table and uploaded to
                    <code>uploads/services</code>.
                </div>

                <form method="post" enctype="multipart/form-data" id="serviceForm">
                    <input type="hidden" name="csrf_token" value="<?= svc_e($csrfToken) ?>">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" value="<?= $editingId ?>">

                    <div class="svc-field">
                        <label for="service_name">Service Name <span>*</span></label>
                        <input
                            class="svc-input"
                            type="text"
                            name="name"
                            id="service_name"
                            maxlength="255"
                            required
                            placeholder="e.g. Industrial Cleaning"
                            value="<?= svc_e($editing['name'] ?? '') ?>"
                        >
                    </div>

                    <div class="svc-field">
                        <label for="service_slug">URL Slug</label>
                        <input
                            class="svc-input"
                            type="text"
                            name="slug"
                            id="service_slug"
                            maxlength="255"
                            placeholder="industrial-cleaning"
                            value="<?= svc_e($editing['slug'] ?? '') ?>"
                        >
                        <span class="svc-help">Unique URL slug automatically generate hoga; zarurat par edit bhi kar sakte hain.</span>
                    </div>

                    <div class="svc-two-col">
                        <div class="svc-field">
                            <label for="parent_id">Parent Service</label>
                            <select class="svc-select" name="parent_id" id="parent_id">
                                <option value="0">— No Parent —</option>
                                <?php foreach ($parentServices as $parent): ?>
                                    <?php if ((int)$parent['id'] === $editingId) continue; ?>
                                    <option
                                        value="<?= (int)$parent['id'] ?>"
                                        <?= (int)($editing['parent_id'] ?? 0) === (int)$parent['id'] ? 'selected' : '' ?>
                                    >
                                        <?= svc_e($parent['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="svc-field">
                            <label for="sort_order">Sort Order</label>
                            <input
                                class="svc-input"
                                type="number"
                                name="sort_order"
                                id="sort_order"
                                value="<?= svc_e($editing['sort_order'] ?? 0) ?>"
                            >
                        </div>
                    </div>

                    <div class="svc-field">
                        <label for="short_description">Short Description</label>
                        <textarea
                            class="svc-textarea"
                            name="short_description"
                            id="short_description"
                            rows="3"
                            placeholder="Write a short introduction..."
                        ><?= svc_e($editing['short_description'] ?? '') ?></textarea>
                    </div>

                    <div class="svc-field">
                        <label for="description">Full Description</label>
                        <textarea
                            class="svc-textarea"
                            name="description"
                            id="description"
                            rows="6"
                            placeholder="Write the full service details..."
                        ><?= svc_e($editing['description'] ?? '') ?></textarea>
                    </div>

                    <div class="svc-field">
                        <label for="service_icon">Icon Class / Name</label>
                        <input
                            class="svc-input"
                            type="text"
                            name="icon"
                            id="service_icon"
                            maxlength="150"
                            placeholder="fa-solid fa-flask"
                            value="<?= svc_e($editing['icon'] ?? '') ?>"
                        >
                        <span class="svc-help">Example: fa-solid fa-flask. Frontend par icon class ko render karna hoga.</span>
                    </div>

                    <div class="svc-two-col">
                        <div class="svc-field">
                            <label for="featured_image">Featured Image</label>
                            <div class="svc-upload">
                                <?php if ($editingFeaturedPath !== ''): ?>
                                    <img
                                        class="svc-existing-image"
                                        src="<?= svc_e(svc_image_url($editingFeaturedPath)) ?>"
                                        alt="Current featured image"
                                    >
                                    <span class="svc-help">Current image. Nayi image select karne par replace hogi.</span>
                                <?php endif; ?>
                                <input type="file" name="featured_image" id="featured_image" accept="image/jpeg,image/png,image/webp,image/gif">
                                <img class="svc-upload-preview" id="featured-preview" alt="Featured image preview">
                                <span class="svc-help">JPG, PNG, WEBP, GIF · Max 5 MB</span>
                            </div>
                        </div>

                        <div class="svc-field">
                            <label for="banner_image">Banner Image</label>
                            <div class="svc-upload">
                                <?php if ($editingBannerPath !== ''): ?>
                                    <img
                                        class="svc-existing-image"
                                        src="<?= svc_e(svc_image_url($editingBannerPath)) ?>"
                                        alt="Current banner image"
                                    >
                                    <span class="svc-help">Current image. Nayi image select karne par replace hogi.</span>
                                <?php endif; ?>
                                <input type="file" name="banner_image" id="banner_image" accept="image/jpeg,image/png,image/webp,image/gif">
                                <img class="svc-upload-preview" id="banner-preview" alt="Banner image preview">
                                <span class="svc-help">JPG, PNG, WEBP, GIF · Max 5 MB</span>
                            </div>
                        </div>
                    </div>

                    <div class="svc-toggle-row">
                        <label class="svc-toggle">
                            <input type="checkbox" name="status" value="1"
                                <?= !isset($editing['status']) || (int)$editing['status'] === 1 ? 'checked' : '' ?>>
                            <i class="fa-solid fa-circle-check"></i> Active
                        </label>

                        <label class="svc-toggle">
                            <input type="checkbox" name="featured" value="1"
                                <?= (int)($editing['featured'] ?? 0) === 1 ? 'checked' : '' ?>>
                            <i class="fa-solid fa-star"></i> Featured
                        </label>
                    </div>

                    <div class="svc-form-actions">
                        <button type="submit" class="svc-btn svc-btn-primary" id="saveButton">
                            <i class="fa-solid fa-floppy-disk"></i>
                            <?= $editing ? 'Update Service' : 'Save Service' ?>
                        </button>

                        <button type="reset" class="svc-btn">
                            <i class="fa-solid fa-rotate-left"></i> Reset
                        </button>

                        <?php if ($editing): ?>
                            <a href="add_service.php" class="svc-btn">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>

                <?php if ($editing): ?>
                    <div class="svc-danger-zone">
                        <h3><i class="fa-solid fa-triangle-exclamation"></i> Danger Zone</h3>
                        <p>Delete karne par service record permanently remove ho jayega. Media files ko yahan se automatically delete nahi kiya jata.</p>

                        <form method="post" class="delete-form"
                              onsubmit="return confirm('Kya aap is service ko permanently delete karna chahte hain?');">
                            <input type="hidden" name="csrf_token" value="<?= svc_e($csrfToken) ?>">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $editingId ?>">
                            <button type="submit" class="svc-btn svc-btn-danger">
                                <i class="fa-solid fa-trash"></i> Delete This Service
                            </button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- SERVICE LIST -->
        <div class="svc-card">
            <div class="svc-card-head">
                <div>
                    <h2><i class="fa-solid fa-list-check"></i> All Services</h2>
                    <p>View, edit and manage your existing services.</p>
                </div>
                <span class="svc-pill active"><?= $totalServices ?> Total</span>
            </div>

            <div class="svc-list-toolbar">
                <div class="svc-search-wrap">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input
                        type="search"
                        class="svc-input svc-search"
                        id="serviceSearch"
                        placeholder="Search services..."
                    >
                </div>
            </div>

            <?php if (!$services): ?>
                <div class="svc-empty">
                    <i class="fa-solid fa-folder-open"></i>
                    <strong>No services yet</strong>
                    <div>Left-side form se apni pehli service add karein.</div>
                </div>
            <?php else: ?>
                <div class="svc-table-wrap">
                    <table class="svc-table" id="serviceTable">
                        <thead>
                        <tr>
                            <th>Service</th>
                            <th>Status</th>
                            <th>Order</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($services as $row): ?>
                            <tr>
                                <td>
                                    <div class="svc-service-name">
                                        <div class="svc-thumb">
                                            <?php if (!empty($row['featured_image_path'])): ?>
                                                <img
                                                    src="<?= svc_e(svc_image_url($row['featured_image_path'])) ?>"
                                                    alt=""
                                                    loading="lazy"
                                                >
                                            <?php elseif (!empty($row['icon'])): ?>
                                                <i class="<?= svc_e($row['icon']) ?>"></i>
                                            <?php else: ?>
                                                <i class="fa-solid fa-flask"></i>
                                            <?php endif; ?>
                                        </div>
                                        <div>
                                            <div class="svc-name"><?= svc_e($row['name']) ?></div>
                                            <div class="svc-slug">/<?= svc_e($row['slug']) ?></div>
                                            <?php if (!empty($row['parent_name'])): ?>
                                                <div class="svc-slug">Parent: <?= svc_e($row['parent_name']) ?></div>
                                            <?php endif; ?>
                                            <?php if ((int)$row['featured'] === 1): ?>
                                                <span class="svc-pill featured"><i class="fa-solid fa-star"></i> Featured</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>

                                <td>
                                    <?php if ((int)$row['status'] === 1): ?>
                                        <span class="svc-pill active">● Active</span>
                                    <?php else: ?>
                                        <span class="svc-pill inactive">● Inactive</span>
                                    <?php endif; ?>
                                </td>

                                <td><?= (int)$row['sort_order'] ?></td>

                                <td>
                                    <div class="svc-row-actions">
                                        <a
                                            class="svc-icon-btn"
                                            href="add_service.php?edit=<?= (int)$row['id'] ?>#service-editor"
                                            title="Edit service"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>

                                        <form method="post" class="delete-form"
                                              onsubmit="return confirm('Kya aap &quot;<?= svc_e($row['name']) ?>&quot; ko delete karna chahte hain?');">
                                            <input type="hidden" name="csrf_token" value="<?= svc_e($csrfToken) ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                            <button class="svc-icon-btn delete" type="submit" title="Delete service">
                                                <i class="fa-solid fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>

                    <div class="svc-empty svc-hidden" id="noSearchResults">
                        <i class="fa-solid fa-magnifying-glass"></i>
                        <strong>No matching services</strong>
                        <div>Dusra search term try karein.</div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

    </section>
</div>
</main>

<script>
(function () {
    const nameInput = document.getElementById('service_name');
    const slugInput = document.getElementById('service_slug');
    let slugManuallyChanged = <?= $editing ? 'true' : 'false' ?>;

    function makeSlug(value) {
        return value
            .toLowerCase()
            .trim()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    if (slugInput) {
        slugInput.addEventListener('input', function () {
            slugManuallyChanged = true;
        });
    }

    if (nameInput && slugInput) {
        nameInput.addEventListener('input', function () {
            if (!slugManuallyChanged || slugInput.value.trim() === '') {
                slugInput.value = makeSlug(nameInput.value);
            }
        });
    }

    function setupPreview(inputId, previewId) {
        const input = document.getElementById(inputId);
        const preview = document.getElementById(previewId);

        if (!input || !preview) return;

        input.addEventListener('change', function () {
            const file = input.files && input.files[0];

            if (!file) {
                preview.style.display = 'none';
                preview.removeAttribute('src');
                return;
            }

            if (!file.type.startsWith('image/')) {
                alert('Please select a valid image.');
                input.value = '';
                preview.style.display = 'none';
                return;
            }

            if (file.size > 5 * 1024 * 1024) {
                alert('Image size 5 MB se kam hona chahiye.');
                input.value = '';
                preview.style.display = 'none';
                return;
            }

            preview.src = URL.createObjectURL(file);
            preview.style.display = 'block';
        });
    }

    setupPreview('featured_image', 'featured-preview');
    setupPreview('banner_image', 'banner-preview');

    const searchInput = document.getElementById('serviceSearch');
    const table = document.getElementById('serviceTable');
    const noResults = document.getElementById('noSearchResults');

    if (searchInput && table) {
        searchInput.addEventListener('input', function () {
            const query = searchInput.value.toLowerCase().trim();
            const rows = table.querySelectorAll('tbody tr');
            let visible = 0;

            rows.forEach(function (row) {
                const match = row.textContent.toLowerCase().includes(query);
                row.style.display = match ? '' : 'none';
                if (match) visible++;
            });

            if (noResults) {
                noResults.classList.toggle('svc-hidden', visible !== 0);
            }

            table.style.display = visible === 0 ? 'none' : '';
        });
    }

    const serviceForm = document.getElementById('serviceForm');
    const saveButton = document.getElementById('saveButton');

    if (serviceForm && saveButton) {
        serviceForm.addEventListener('submit', function () {
            if (!serviceForm.checkValidity()) return;

            saveButton.disabled = true;
            saveButton.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';
        });
    }
})();
</script>
</body>
</html>