<?php
/**
 * admin/testimonials.php
 *
 * Pure Chemical - Testimonials Management
 * Premium Modern Admin UI
 *
 * Uses existing `testimonials` table only.
 * No new table / no duplicate data structure.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

/* ---------------------------------------------------------
   Helpers
--------------------------------------------------------- */

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function redirectSelf($extra = '')
{
    $url = basename($_SERVER['PHP_SELF']);

    if ($extra !== '') {
        $url .= '?' . ltrim($extra, '?');
    }

    header('Location: ' . $url);
    exit;
}

function getCsrfToken()
{
    if (function_exists('csrf_token')) {
        return csrf_token();
    }

    if (function_exists('csrf_field')) {
        if (!isset($_SESSION['_csrf_fallback'])) {
            $_SESSION['_csrf_fallback'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['_csrf_fallback'];
    }

    if (empty($_SESSION['_csrf_fallback'])) {
        $_SESSION['_csrf_fallback'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['_csrf_fallback'];
}

function verifyCsrfToken($token)
{
    if (function_exists('csrf_verify')) {
        return csrf_verify($token);
    }

    if (empty($_SESSION['_csrf_fallback'])) {
        return false;
    }

    return hash_equals($_SESSION['_csrf_fallback'], (string)$token);
}

function flashMessage($type, $message)
{
    $_SESSION['testimonial_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function getFlashMessage()
{
    $flash = $_SESSION['testimonial_flash'] ?? null;
    unset($_SESSION['testimonial_flash']);

    return $flash;
}

/* ---------------------------------------------------------
   CSRF
--------------------------------------------------------- */

$csrfToken = getCsrfToken();

/* ---------------------------------------------------------
   POST Actions
--------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $postedToken = $_POST['csrf_token'] ?? '';

    if (!verifyCsrfToken($postedToken)) {
        flashMessage('error', 'Security token expired. Please try again.');
        redirectSelf();
    }

    $action = $_POST['action'] ?? '';

    /* -----------------------------------------------------
       SAVE / ADD / UPDATE
    ----------------------------------------------------- */

    if ($action === 'save') {

        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

        $name = trim($_POST['name'] ?? '');
        $designation = trim($_POST['designation'] ?? '');
        $company = trim($_POST['company'] ?? '');
        $content = trim($_POST['content'] ?? '');

        $imageIdRaw = trim($_POST['image_id'] ?? '');
        $imageId = $imageIdRaw !== '' ? (int)$imageIdRaw : null;

        $ratingRaw = trim($_POST['rating'] ?? '');
        $rating = $ratingRaw !== '' ? (float)$ratingRaw : null;

        $status = isset($_POST['status']) ? 1 : 0;
        $featured = isset($_POST['featured']) ? 1 : 0;

        $sortOrder = isset($_POST['sort_order'])
            ? (int)$_POST['sort_order']
            : 0;

        $errors = [];

        if ($name === '') {
            $errors[] = 'Name is required.';
        }

        if ($content === '') {
            $errors[] = 'Testimonial content is required.';
        }

        if ($rating !== null && ($rating < 0 || $rating > 5)) {
            $errors[] = 'Rating must be between 0 and 5.';
        }

        if ($imageId !== null && $imageId < 1) {
            $imageId = null;
        }

        if ($sortOrder < 0) {
            $sortOrder = 0;
        }

        if (!empty($errors)) {
            flashMessage('error', implode(' ', $errors));
            redirectSelf($id > 0 ? 'edit=' . $id : 'add=1');
        }

        try {

            // A newly uploaded image takes priority over the selected Media Library image.
            if (isset($_FILES['testimonial_image']) &&
                ($_FILES['testimonial_image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {

                $upload = $_FILES['testimonial_image'];
                if (($upload['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
                    throw new RuntimeException('Image upload failed. Please choose the image again.');
                }
                if (($upload['size'] ?? 0) > 8 * 1024 * 1024) {
                    throw new RuntimeException('Image must be 8 MB or smaller.');
                }

                $tmpPath = $upload['tmp_name'] ?? '';
                if (!is_uploaded_file($tmpPath)) {
                    throw new RuntimeException('Invalid uploaded image.');
                }
                $imageInfo = @getimagesize($tmpPath);
                $mime = $imageInfo['mime'] ?? '';
                $allowedMimes = [
                    'image/jpeg' => 'jpg',
                    'image/png'  => 'png',
                    'image/gif'  => 'gif',
                    'image/webp' => 'webp'
                ];
                if (!isset($allowedMimes[$mime])) {
                    throw new RuntimeException('Only JPG, PNG, GIF and WEBP images are allowed.');
                }

                $uploadDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'media';
                if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
                    throw new RuntimeException('Could not create uploads/media folder.');
                }
                $fileName = 'testimonial_' . bin2hex(random_bytes(12)) . '.' . $allowedMimes[$mime];
                $destination = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
                if (!move_uploaded_file($tmpPath, $destination)) {
                    throw new RuntimeException('Could not save image. Check uploads folder permissions.');
                }

                $originalName = basename((string)($upload['name'] ?? $fileName));
                $relativePath = 'uploads/media/' . $fileName;
                $width = isset($imageInfo[0]) ? (int)$imageInfo[0] : null;
                $height = isset($imageInfo[1]) ? (int)$imageInfo[1] : null;
                try {
                    $mediaStmt = $pdo->prepare("INSERT INTO media
                        (original_name, file_name, file_path, mime_type, file_type, extension, file_size, width, height, alt_text, title, caption, uploaded_by, status)
                        VALUES (:original_name, :file_name, :file_path, :mime_type, 'image', :extension, :file_size, :width, :height, :alt_text, :title, NULL, NULL, 1)");
                    $mediaStmt->execute([
                        ':original_name' => mb_substr($originalName, 0, 255),
                        ':file_name' => $fileName,
                        ':file_path' => $relativePath,
                        ':mime_type' => $mime,
                        ':extension' => $allowedMimes[$mime],
                        ':file_size' => (int)filesize($destination),
                        ':width' => $width,
                        ':height' => $height,
                        ':alt_text' => mb_substr($name, 0, 255),
                        ':title' => mb_substr($originalName, 0, 255)
                    ]);
                    $imageId = (int)$pdo->lastInsertId();
                } catch (Throwable $mediaError) {
                    @unlink($destination);
                    throw $mediaError;
                }
            }

            // Never save a media ID that does not exist in the media library.
            if ($imageId !== null) {
                $checkMedia = $pdo->prepare("SELECT id FROM media WHERE id = :id AND file_type = 'image' LIMIT 1");
                $checkMedia->execute([':id' => $imageId]);
                if (!$checkMedia->fetchColumn()) {
                    throw new RuntimeException('Selected image was not found in the media library. Please choose a valid image.');
                }
            }

            if ($id > 0) {

                $stmt = $pdo->prepare("
                    UPDATE testimonials
                    SET
                        name = :name,
                        designation = :designation,
                        company = :company,
                        content = :content,
                        image_id = :image_id,
                        rating = :rating,
                        status = :status,
                        featured = :featured,
                        sort_order = :sort_order
                    WHERE id = :id
                    LIMIT 1
                ");

                $stmt->execute([
                    ':name' => $name,
                    ':designation' => $designation !== '' ? $designation : null,
                    ':company' => $company !== '' ? $company : null,
                    ':content' => $content,
                    ':image_id' => $imageId,
                    ':rating' => $rating,
                    ':status' => $status,
                    ':featured' => $featured,
                    ':sort_order' => $sortOrder,
                    ':id' => $id
                ]);

                flashMessage('success', 'Testimonial updated successfully.');

            } else {

                $stmt = $pdo->prepare("
                    INSERT INTO testimonials
                    (
                        name,
                        designation,
                        company,
                        content,
                        image_id,
                        rating,
                        status,
                        featured,
                        sort_order
                    )
                    VALUES
                    (
                        :name,
                        :designation,
                        :company,
                        :content,
                        :image_id,
                        :rating,
                        :status,
                        :featured,
                        :sort_order
                    )
                ");

                $stmt->execute([
                    ':name' => $name,
                    ':designation' => $designation !== '' ? $designation : null,
                    ':company' => $company !== '' ? $company : null,
                    ':content' => $content,
                    ':image_id' => $imageId,
                    ':rating' => $rating,
                    ':status' => $status,
                    ':featured' => $featured,
                    ':sort_order' => $sortOrder
                ]);

                flashMessage('success', 'Testimonial added successfully.');
            }

        } catch (Throwable $e) {

            error_log('Testimonials Save Error: ' . $e->getMessage());

            flashMessage('error', $e instanceof RuntimeException
                ? $e->getMessage()
                : 'Unable to save testimonial. Please check the database structure and media table.');
        }

        redirectSelf();
    }

    /* -----------------------------------------------------
       DELETE
    ----------------------------------------------------- */

    if ($action === 'delete') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id < 1) {
            flashMessage('error', 'Invalid testimonial ID.');
            redirectSelf();
        }

        try {

            $stmt = $pdo->prepare("
                DELETE FROM testimonials
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            flashMessage('success', 'Testimonial deleted successfully.');

        } catch (PDOException $e) {

            error_log('Testimonials Delete Error: ' . $e->getMessage());

            flashMessage(
                'error',
                'Unable to delete testimonial.'
            );
        }

        redirectSelf();
    }

    /* -----------------------------------------------------
       TOGGLE STATUS
    ----------------------------------------------------- */

    if ($action === 'toggle_status') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id < 1) {
            flashMessage('error', 'Invalid testimonial ID.');
            redirectSelf();
        }

        try {

            $stmt = $pdo->prepare("
                UPDATE testimonials
                SET status = CASE
                    WHEN status = 1 THEN 0
                    ELSE 1
                END
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            flashMessage('success', 'Testimonial status updated.');

        } catch (PDOException $e) {

            error_log('Testimonials Status Error: ' . $e->getMessage());

            flashMessage(
                'error',
                'Unable to update status.'
            );
        }

        redirectSelf();
    }

    /* -----------------------------------------------------
       TOGGLE FEATURED
    ----------------------------------------------------- */

    if ($action === 'toggle_featured') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id < 1) {
            flashMessage('error', 'Invalid testimonial ID.');
            redirectSelf();
        }

        try {

            $stmt = $pdo->prepare("
                UPDATE testimonials
                SET featured = CASE
                    WHEN featured = 1 THEN 0
                    ELSE 1
                END
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            flashMessage('success', 'Featured status updated.');

        } catch (PDOException $e) {

            error_log('Testimonials Featured Error: ' . $e->getMessage());

            flashMessage(
                'error',
                'Unable to update featured status.'
            );
        }

        redirectSelf();
    }
}

/* ---------------------------------------------------------
   Edit Record
--------------------------------------------------------- */

$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editTestimonial = null;

if ($editId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            name,
            designation,
            company,
            content,
            image_id,
            rating,
            status,
            featured,
            sort_order,
            created_at,
            updated_at
        FROM testimonials
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $editId
    ]);

    $editTestimonial = $stmt->fetch();

    if (!$editTestimonial) {
        flashMessage('error', 'Testimonial not found.');
        redirectSelf();
    }
}

/* ---------------------------------------------------------
   Filters
--------------------------------------------------------- */

$search = trim($_GET['search'] ?? '');
$statusFilter = $_GET['status'] ?? '';
$featuredFilter = $_GET['featured'] ?? '';

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPageOptions = [10, 20, 30, 50];

$perPage = (int)($_GET['per_page'] ?? 20);

if (!in_array($perPage, $perPageOptions, true)) {
    $perPage = 20;
}

$offset = ($page - 1) * $perPage;

/* ---------------------------------------------------------
   Statistics
--------------------------------------------------------- */

$stats = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
    'featured' => 0
];

try {

    $stmt = $pdo->query("
        SELECT
            COUNT(*) AS total,
            COALESCE(SUM(status = 1), 0) AS active,
            COALESCE(SUM(status = 0), 0) AS inactive,
            COALESCE(SUM(featured = 1), 0) AS featured
        FROM testimonials
    ");

    $stats = $stmt->fetch() ?: $stats;

} catch (PDOException $e) {

    error_log('Testimonials Stats Error: ' . $e->getMessage());
}

/* ---------------------------------------------------------
   Build List Query
--------------------------------------------------------- */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            name LIKE :search
            OR designation LIKE :search
            OR company LIKE :search
            OR content LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {

    $where[] = "status = :status";
    $params[':status'] = (int)$statusFilter;
}

if ($featuredFilter !== '' && in_array($featuredFilter, ['0', '1'], true)) {

    $where[] = "featured = :featured";
    $params[':featured'] = (int)$featuredFilter;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/* ---------------------------------------------------------
   Total Rows
--------------------------------------------------------- */

$totalRows = 0;

try {

    $countSql = "
        SELECT COUNT(*)
        FROM testimonials
        {$whereSql}
    ";

    $stmt = $pdo->prepare($countSql);
    $stmt->execute($params);

    $totalRows = (int)$stmt->fetchColumn();

} catch (PDOException $e) {

    error_log('Testimonials Count Error: ' . $e->getMessage());
}

$totalPages = max(
    1,
    (int)ceil($totalRows / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

/* ---------------------------------------------------------
   Testimonials
--------------------------------------------------------- */

$testimonials = [];

try {

    $sql = "
        SELECT
            id,
            name,
            designation,
            company,
            content,
            image_id,
            rating,
            status,
            featured,
            sort_order,
            created_at,
            updated_at
        FROM testimonials
        {$whereSql}
        ORDER BY
            featured DESC,
            sort_order ASC,
            id DESC
        LIMIT :limit OFFSET :offset
    ";

    $stmt = $pdo->prepare($sql);

    foreach ($params as $key => $value) {
        $stmt->bindValue(
            $key,
            $value,
            is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR
        );
    }

    $stmt->bindValue(
        ':limit',
        $perPage,
        PDO::PARAM_INT
    );

    $stmt->bindValue(
        ':offset',
        $offset,
        PDO::PARAM_INT
    );

    $stmt->execute();

    $testimonials = $stmt->fetchAll();

} catch (PDOException $e) {

    error_log('Testimonials List Error: ' . $e->getMessage());
}

/* ---------------------------------------------------------
   Flash
--------------------------------------------------------- */

$flash = getFlashMessage();

/* ---------------------------------------------------------
   Media Library images for the image selector
--------------------------------------------------------- */

$mediaImages = [];
try {
    $mediaStmt = $pdo->query("SELECT id, original_name, file_name, file_path, mime_type, title
        FROM media WHERE status = 1 AND file_type = 'image' ORDER BY id DESC LIMIT 1000");
    $mediaImages = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log('Testimonials Media List Error: ' . $e->getMessage());
}

$mediaById = [];
foreach ($mediaImages as $mediaImage) {
    $mediaById[(int)$mediaImage['id']] = $mediaImage;
}

/* ---------------------------------------------------------
   Form Defaults
--------------------------------------------------------- */

$formData = [
    'id' => 0,
    'name' => '',
    'designation' => '',
    'company' => '',
    'content' => '',
    'image_id' => '',
    'rating' => '',
    'status' => 1,
    'featured' => 0,
    'sort_order' => 0
];

if ($editTestimonial) {

    $formData = [
        'id' => (int)$editTestimonial['id'],
        'name' => $editTestimonial['name'],
        'designation' => $editTestimonial['designation'],
        'company' => $editTestimonial['company'],
        'content' => $editTestimonial['content'],
        'image_id' => $editTestimonial['image_id'],
        'rating' => $editTestimonial['rating'],
        'status' => (int)$editTestimonial['status'],
        'featured' => (int)$editTestimonial['featured'],
        'sort_order' => (int)$editTestimonial['sort_order']
    ];
}

/* ---------------------------------------------------------
   Query String Helper
--------------------------------------------------------- */

function pageUrl($pageNumber)
{
    $query = $_GET;

    $query['page'] = $pageNumber;

    return '?' . http_build_query($query);
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Testimonials | Pure Chemical Admin
    </title>

    <meta
        name="theme-color"
        content="#0f172a"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #0f766e;
            --primary-dark: #115e59;
            --primary-light: #ccfbf1;

            --dark: #0f172a;
            --dark-2: #1e293b;

            --muted: #64748b;
            --muted-light: #94a3b8;

            --bg: #f8fafc;
            --white: #ffffff;

            --border: #e2e8f0;

            --success: #15803d;
            --success-bg: #dcfce7;

            --danger: #dc2626;
            --danger-bg: #fee2e2;

            --warning: #d97706;
            --warning-bg: #fef3c7;

            --blue: #2563eb;
            --blue-bg: #dbeafe;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .05);

            --shadow:
                0 10px 35px rgba(15, 23, 42, .07);

            --radius:
                18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background: var(--bg);
            color: var(--dark);
            font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        button,
        input,
        textarea,
        select {
            font-family: inherit;
        }

        button {
            cursor: pointer;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        /* ----------------------------------------------
           Main Layout
        ---------------------------------------------- */

        .page-shell {
            min-height: 100vh;
            margin-left: 280px;
        }

        .topbar {
            position: sticky;
            top: 0;
            z-index: 100;
            height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 30px;

            background: rgba(255,255,255,.92);
            backdrop-filter: blur(18px);

            border-bottom: 1px solid rgba(226,232,240,.9);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .page-icon {
            width: 44px;
            height: 44px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 14px;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #14b8a6
                );

            color: white;

            box-shadow:
                0 8px 20px rgba(13,148,136,.22);
        }

        .topbar-title {
            font-size: 16px;
            font-weight: 800;
            letter-spacing: -.02em;
        }

        .topbar-subtitle {
            margin-top: 3px;
            color: var(--muted);
            font-size: 12px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .admin-pill {
            display: flex;
            align-items: center;
            gap: 9px;

            padding: 8px 12px;

            border: 1px solid var(--border);
            border-radius: 12px;

            background: white;
        }

        .admin-avatar {
            width: 32px;
            height: 32px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 10px;

            background: var(--dark);
            color: white;

            font-size: 12px;
            font-weight: 800;
        }

        .admin-name {
            font-size: 12px;
            font-weight: 700;
        }

        /* ----------------------------------------------
           Content
        ---------------------------------------------- */

        .content {
            padding: 30px;
            max-width: 1700px;
            margin: 0 auto;
        }

        .hero {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;

            gap: 24px;

            margin-bottom: 25px;
        }

        .hero h1 {
            margin: 0;
            font-size: 31px;
            line-height: 1.15;

            letter-spacing: -.04em;
        }

        .hero p {
            margin: 9px 0 0;

            max-width: 680px;

            color: var(--muted);
            font-size: 14px;
            line-height: 1.7;
        }

        .hero-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* ----------------------------------------------
           Buttons
        ---------------------------------------------- */

        .btn {
            min-height: 42px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            gap: 8px;

            padding: 0 15px;

            border-radius: 12px;

            border: 1px solid transparent;

            font-size: 13px;
            font-weight: 700;

            transition:
                transform .18s ease,
                box-shadow .18s ease,
                background .18s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-primary {
            color: white;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #0d9488
                );

            box-shadow:
                0 8px 18px rgba(13,148,136,.18);
        }

        .btn-secondary {
            background: white;
            border-color: var(--border);
            color: var(--dark-2);
        }

        .btn-danger {
            background: var(--danger-bg);
            color: var(--danger);
            border-color: #fecaca;
        }

        .btn-sm {
            min-height: 36px;
            padding: 0 11px;
            border-radius: 10px;
            font-size: 12px;
        }

        /* ----------------------------------------------
           Stats
        ---------------------------------------------- */

        .stats-grid {
            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 20px;
        }

        .stat-card {
            position: relative;

            overflow: hidden;

            background: white;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            padding: 20px;

            box-shadow: var(--shadow-sm);
        }

        .stat-card::after {
            content: "";

            position: absolute;

            width: 90px;
            height: 90px;

            right: -35px;
            bottom: -35px;

            border-radius: 50%;

            background: rgba(15,118,110,.06);
        }

        .stat-top {
            display: flex;
            align-items: center;
            justify-content: space-between;

            margin-bottom: 16px;
        }

        .stat-icon {
            width: 40px;
            height: 40px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 12px;

            background: var(--primary-light);
            color: var(--primary);
        }

        .stat-label {
            color: var(--muted);

            font-size: 12px;
            font-weight: 700;

            text-transform: uppercase;
            letter-spacing: .05em;
        }

        .stat-value {
            font-size: 26px;
            font-weight: 800;
            letter-spacing: -.04em;
        }

        /* ----------------------------------------------
           Alert
        ---------------------------------------------- */

        .alert {
            display: flex;
            align-items: flex-start;

            gap: 11px;

            padding: 14px 16px;

            margin-bottom: 18px;

            border-radius: 14px;

            font-size: 13px;
            font-weight: 600;
        }

        .alert-success {
            color: #166534;
            background: var(--success-bg);
            border: 1px solid #bbf7d0;
        }

        .alert-error {
            color: #991b1b;
            background: var(--danger-bg);
            border: 1px solid #fecaca;
        }

        /* ----------------------------------------------
           Filters
        ---------------------------------------------- */

        .filter-card {
            padding: 18px;

            background: white;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);

            margin-bottom: 18px;
        }

        .filter-form {
            display: grid;

            grid-template-columns:
                minmax(220px, 1fr)
                180px
                180px
                130px
                auto;

            gap: 10px;
        }

        .input-wrap {
            position: relative;
        }

        .input-icon {
            position: absolute;

            left: 13px;
            top: 50%;

            transform: translateY(-50%);

            color: var(--muted-light);

            pointer-events: none;
        }

        .form-control,
        .form-select,
        .form-textarea {
            width: 100%;

            border: 1px solid var(--border);

            background: #fff;

            border-radius: 12px;

            outline: none;

            color: var(--dark);

            font-size: 13px;

            transition:
                border-color .18s ease,
                box-shadow .18s ease;
        }

        .form-control,
        .form-select {
            height: 44px;
            padding: 0 13px;
        }

        .has-icon .form-control {
            padding-left: 39px;
        }

        .form-textarea {
            min-height: 145px;

            padding: 13px;

            resize: vertical;

            line-height: 1.65;
        }

        .form-control:focus,
        .form-select:focus,
        .form-textarea:focus {
            border-color: #14b8a6;

            box-shadow:
                0 0 0 4px rgba(20,184,166,.10);
        }

        /* ----------------------------------------------
           Table
        ---------------------------------------------- */

        .table-card {
            overflow: hidden;

            background: white;

            border: 1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);
        }

        .table-header {
            display: flex;

            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 19px 20px;

            border-bottom: 1px solid var(--border);
        }

        .table-title {
            font-size: 14px;
            font-weight: 800;
        }

        .table-count {
            color: var(--muted);
            font-size: 12px;
            margin-top: 4px;
        }

        .table-scroll {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;

            min-width: 1050px;
        }

        th {
            padding: 13px 18px;

            text-align: left;

            background: #f8fafc;

            color: var(--muted);

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;

            letter-spacing: .07em;

            border-bottom: 1px solid var(--border);

            white-space: nowrap;
        }

        td {
            padding: 15px 18px;

            border-bottom: 1px solid #eef2f7;

            vertical-align: middle;

            font-size: 13px;
        }

        tr:last-child td {
            border-bottom: 0;
        }

        tbody tr {
            transition: background .15s ease;
        }

        tbody tr:hover {
            background: #fbfefd;
        }

        .person {
            display: flex;
            align-items: center;

            gap: 11px;

            min-width: 230px;
        }

        .avatar {
            width: 42px;
            height: 42px;

            flex: 0 0 42px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 13px;

            background:
                linear-gradient(
                    135deg,
                    #ccfbf1,
                    #99f6e4
                );

            color: #115e59;

            font-weight: 800;

            overflow: hidden;
        }

        .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .avatar span { align-items: center; justify-content: center; width: 100%; height: 100%; }

        .person-name {
            font-weight: 800;
            color: var(--dark);
        }

        .person-meta {
            margin-top: 3px;

            color: var(--muted);

            font-size: 11px;

            white-space: nowrap;
        }

        .content-preview {
            max-width: 390px;

            color: #475569;

            line-height: 1.55;

            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;

            overflow: hidden;
        }

        .company {
            color: var(--muted);
            font-size: 12px;
        }

        /* ----------------------------------------------
           Badges
        ---------------------------------------------- */

        .badge {
            display: inline-flex;

            align-items: center;

            gap: 6px;

            min-height: 28px;

            padding: 0 9px;

            border-radius: 999px;

            font-size: 10px;
            font-weight: 800;

            white-space: nowrap;
        }

        .badge-active {
            color: #166534;
            background: var(--success-bg);
        }

        .badge-inactive {
            color: #991b1b;
            background: var(--danger-bg);
        }

        .badge-featured {
            color: #92400e;
            background: var(--warning-bg);
        }

        .badge-normal {
            color: #475569;
            background: #f1f5f9;
        }

        /* ----------------------------------------------
           Rating
        ---------------------------------------------- */

        .rating {
            display: inline-flex;
            align-items: center;
            gap: 2px;

            color: #f59e0b;
        }

        .rating-number {
            margin-left: 5px;

            color: var(--dark);

            font-size: 12px;
            font-weight: 800;
        }

        .muted {
            color: var(--muted-light);
        }

        /* ----------------------------------------------
           Actions
        ---------------------------------------------- */

        .actions {
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .icon-btn {
            width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);

            border-radius: 10px;

            background: white;

            color: var(--muted);

            transition:
                .18s ease;
        }

        .icon-btn:hover {
            color: var(--primary);
            border-color: #99f6e4;
            background: #f0fdfa;
        }

        .icon-btn.danger:hover {
            color: var(--danger);
            border-color: #fecaca;
            background: #fff1f2;
        }

        .inline-form {
            display: inline;
            margin: 0;
            padding: 0;
        }

        /* ----------------------------------------------
           Empty
        ---------------------------------------------- */

        .empty {
            text-align: center;

            padding: 65px 25px;
        }

        .empty-icon {
            width: 62px;
            height: 62px;

            margin: 0 auto 15px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 18px;

            background: #f1f5f9;
            color: #94a3b8;

            font-size: 22px;
        }

        .empty h3 {
            margin: 0;

            font-size: 16px;
        }

        .empty p {
            margin: 7px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        /* ----------------------------------------------
           Pagination
        ---------------------------------------------- */

        .pagination {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 15px 18px;

            border-top: 1px solid var(--border);
        }

        .pagination-info {
            color: var(--muted);
            font-size: 12px;
        }

        .pagination-links {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .page-link {
            min-width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);

            border-radius: 9px;

            background: white;

            color: var(--muted);

            font-size: 12px;
            font-weight: 700;
        }

        .page-link:hover,
        .page-link.active {
            color: white;
            background: var(--primary);
            border-color: var(--primary);
        }

        .page-link.disabled {
            opacity: .45;
            pointer-events: none;
        }

        /* ----------------------------------------------
           Modal
        ---------------------------------------------- */

        .modal-backdrop {
            position: fixed;

            inset: 0;

            z-index: 9999;

            display: none;

            align-items: center;
            justify-content: center;

            padding: 25px;

            background: rgba(15,23,42,.60);

            backdrop-filter: blur(7px);
        }

        .modal-backdrop.show {
            display: flex;
        }

        .modal {
            width: min(760px, 100%);

            max-height: calc(100vh - 50px);

            overflow-y: auto;

            background: white;

            border-radius: 22px;

            box-shadow:
                0 30px 80px rgba(15,23,42,.25);

            animation:
                modalIn .22s ease;
        }

        @keyframes modalIn {
            from {
                opacity: 0;
                transform: translateY(15px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {
            display: flex;

            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 20px 22px;

            border-bottom: 1px solid var(--border);
        }

        .modal-title {
            font-size: 17px;
            font-weight: 800;
        }

        .modal-subtitle {
            margin-top: 4px;

            color: var(--muted);

            font-size: 12px;
        }

        .modal-close {
            width: 36px;
            height: 36px;

            border: 0;

            border-radius: 10px;

            background: #f1f5f9;

            color: var(--muted);
        }

        .modal-body {
            padding: 22px;
        }

        .modal-footer {
            display: flex;

            justify-content: flex-end;

            gap: 9px;

            padding: 17px 22px;

            border-top: 1px solid var(--border);
        }

        .form-grid {
            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 16px;
        }

        .form-group {
            margin-bottom: 0;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-label {
            display: block;

            margin-bottom: 7px;

            font-size: 12px;
            font-weight: 800;

            color: #334155;
        }

        .required {
            color: var(--danger);
        }

        .form-help {
            margin-top: 6px;

            color: var(--muted-light);

            font-size: 11px;

            line-height: 1.5;
        }

        .switch-row {
            display: flex;

            gap: 12px;

            flex-wrap: wrap;

            margin-top: 4px;
        }

        .switch-box {
            display: inline-flex;
            align-items: center;
            gap: 9px;

            padding: 10px 12px;

            border: 1px solid var(--border);

            border-radius: 12px;

            background: #f8fafc;

            cursor: pointer;
        }

        .switch-box input {
            accent-color: var(--primary);
        }

        .switch-text {
            font-size: 12px;
            font-weight: 700;
        }

        /* ----------------------------------------------
           Responsive
        ---------------------------------------------- */

        @media (max-width: 1200px) {

            .filter-form {
                grid-template-columns:
                    1fr
                    1fr
                    1fr;
            }

            .filter-form .search-field {
                grid-column: 1 / -1;
            }

        }

        @media (max-width: 1050px) {

            .page-shell {
                margin-left: 0;
            }

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

        }

        @media (max-width: 700px) {

            .topbar {
                padding: 0 15px;
            }

            .admin-pill {
                display: none;
            }

            .content {
                padding: 20px 14px;
            }

            .hero {
                align-items: flex-start;

                flex-direction: column;
            }

            .hero h1 {
                font-size: 25px;
            }

            .hero-actions {
                width: 100%;
            }

            .hero-actions .btn {
                flex: 1;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .filter-form {
                grid-template-columns: 1fr;
            }

            .filter-form .search-field {
                grid-column: auto;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-group.full {
                grid-column: auto;
            }

            .modal-backdrop {
                padding: 10px;
            }

            .modal {
                max-height: calc(100vh - 20px);
                border-radius: 18px;
            }

            .pagination {
                flex-direction: column;
                align-items: flex-start;
            }

        }

    </style>
</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing Sidebar
|--------------------------------------------------------------------------
|
| Sidebar intentionally included separately.
| No admin/header.php is included here.
|
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="page-shell">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="page-icon">
                <i class="fa-solid fa-quote-left"></i>
            </div>

            <div>
                <div class="topbar-title">
                    Testimonials
                </div>

                <div class="topbar-subtitle">
                    Customer reviews & social proof
                </div>
            </div>

        </div>

        <div class="topbar-right">

            <div class="admin-pill">

                <div class="admin-avatar">
                    <?php
                    $adminName = $_SESSION['ADMIN_NAME']
                        ?? $_SESSION['admin_name']
                        ?? 'Admin';

                    echo h(
                        strtoupper(
                            substr(
                                trim($adminName),
                                0,
                                1
                            )
                        )
                    );
                    ?>
                </div>

                <div class="admin-name">
                    <?php echo h($adminName); ?>
                </div>

            </div>

        </div>

    </header>

    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="content">

        <!-- HERO -->

        <section class="hero">

            <div>

                <h1>
                    Testimonials
                </h1>

                <p>
                    Manage customer testimonials, ratings,
                    featured reviews and display ordering
                    from one premium workspace.
                </p>

            </div>

            <div class="hero-actions">

                <button
                    type="button"
                    class="btn btn-primary"
                    onclick="openTestimonialModal()"
                >
                    <i class="fa-solid fa-plus"></i>
                    Add Testimonial
                </button>

            </div>

        </section>

        <!-- FLASH -->

        <?php if ($flash): ?>

            <div
                class="alert <?php echo $flash['type'] === 'success'
                    ? 'alert-success'
                    : 'alert-error'; ?>"
            >

                <i
                    class="fa-solid <?php echo $flash['type'] === 'success'
                        ? 'fa-circle-check'
                        : 'fa-circle-exclamation'; ?>"
                ></i>

                <div>
                    <?php echo h($flash['message']); ?>
                </div>

            </div>

        <?php endif; ?>

        <!-- STATS -->

        <section class="stats-grid">

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Total
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-comments"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?php echo number_format((int)$stats['total']); ?>
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Active
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-check"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?php echo number_format((int)$stats['active']); ?>
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Inactive
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-eye-slash"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?php echo number_format((int)$stats['inactive']); ?>
                </div>

            </div>

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-label">
                        Featured
                    </div>

                    <div class="stat-icon">
                        <i class="fa-solid fa-star"></i>
                    </div>

                </div>

                <div class="stat-value">
                    <?php echo number_format((int)$stats['featured']); ?>
                </div>

            </div>

        </section>

        <!-- FILTERS -->

        <section class="filter-card">

            <form
                method="GET"
                class="filter-form"
            >

                <div class="input-wrap has-icon search-field">

                    <i class="fa-solid fa-magnifying-glass input-icon"></i>

                    <input
                        type="search"
                        name="search"
                        class="form-control"
                        placeholder="Search by name, designation, company or content..."
                        value="<?php echo h($search); ?>"
                    >

                </div>

                <select
                    name="status"
                    class="form-select"
                >

                    <option value="">
                        All Status
                    </option>

                    <option
                        value="1"
                        <?php echo $statusFilter === '1' ? 'selected' : ''; ?>
                    >
                        Active
                    </option>

                    <option
                        value="0"
                        <?php echo $statusFilter === '0' ? 'selected' : ''; ?>
                    >
                        Inactive
                    </option>

                </select>

                <select
                    name="featured"
                    class="form-select"
                >

                    <option value="">
                        All Testimonials
                    </option>

                    <option
                        value="1"
                        <?php echo $featuredFilter === '1' ? 'selected' : ''; ?>
                    >
                        Featured
                    </option>

                    <option
                        value="0"
                        <?php echo $featuredFilter === '0' ? 'selected' : ''; ?>
                    >
                        Normal
                    </option>

                </select>

                <select
                    name="per_page"
                    class="form-select"
                >

                    <?php foreach ($perPageOptions as $option): ?>

                        <option
                            value="<?php echo $option; ?>"
                            <?php echo $perPage === $option
                                ? 'selected'
                                : ''; ?>
                        >
                            <?php echo $option; ?> / page
                        </option>

                    <?php endforeach; ?>

                </select>

                <button
                    type="submit"
                    class="btn btn-secondary"
                >
                    <i class="fa-solid fa-filter"></i>
                    Filter
                </button>

            </form>

        </section>

        <!-- TABLE -->

        <section class="table-card">

            <div class="table-header">

                <div>

                    <div class="table-title">
                        All Testimonials
                    </div>

                    <div class="table-count">
                        <?php echo number_format($totalRows); ?>
                        record<?php echo $totalRows === 1 ? '' : 's'; ?>
                        found
                    </div>

                </div>

                <?php if ($search !== '' || $statusFilter !== '' || $featuredFilter !== ''): ?>

                    <a
                        href="<?php echo h(basename($_SERVER['PHP_SELF'])); ?>"
                        class="btn btn-secondary btn-sm"
                    >
                        <i class="fa-solid fa-rotate-left"></i>
                        Reset
                    </a>

                <?php endif; ?>

            </div>

            <div class="table-scroll">

                <?php if (empty($testimonials)): ?>

                    <div class="empty">

                        <div class="empty-icon">
                            <i class="fa-regular fa-comments"></i>
                        </div>

                        <h3>
                            No testimonials found
                        </h3>

                        <p>
                            Add your first customer testimonial
                            to start building social proof.
                        </p>

                    </div>

                <?php else: ?>

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    Customer
                                </th>

                                <th>
                                    Testimonial
                                </th>

                                <th>
                                    Rating
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Featured
                                </th>

                                <th>
                                    Sort
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($testimonials as $testimonial): ?>

                            <?php

                            $name = trim(
                                (string)$testimonial['name']
                            );

                            $initial = strtoupper(
                                substr(
                                    $name !== ''
                                        ? $name
                                        : 'T',
                                    0,
                                    1
                                )
                            );

                            $designation =
                                trim(
                                    (string)($testimonial['designation'] ?? '')
                                );

                            $company =
                                trim(
                                    (string)($testimonial['company'] ?? '')
                                );

                            $content =
                                trim(
                                    (string)$testimonial['content']
                                );

                            $rating =
                                $testimonial['rating'] !== null
                                    ? (float)$testimonial['rating']
                                    : null;

                            ?>

                            <tr>

                                <!-- CUSTOMER -->

                                <td>

                                    <div class="person">

                                        <div class="avatar">

                                            <?php
                                                $rowMedia = !empty($testimonial['image_id'])
                                                    ? ($mediaById[(int)$testimonial['image_id']] ?? null)
                                                    : null;
                                                $rowImagePath = $rowMedia ? ltrim((string)$rowMedia['file_path'], '/') : '';
                                            ?>
                                            <?php if ($rowMedia && $rowImagePath !== ''): ?>
                                                <img src="../<?php echo h($rowImagePath); ?>" alt="<?php echo h($name); ?>" loading="lazy" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                                <span style="display:none"><?php echo h($initial); ?></span>
                                            <?php else: ?>

                                                <span>
                                                    <?php echo h($initial); ?>
                                                </span>

                                            <?php endif; ?>

                                        </div>

                                        <div>

                                            <div class="person-name">
                                                <?php echo h($name); ?>
                                            </div>

                                            <?php if ($designation !== ''): ?>

                                                <div class="person-meta">
                                                    <?php echo h($designation); ?>
                                                </div>

                                            <?php endif; ?>

                                            <?php if ($company !== ''): ?>

                                                <div class="person-meta">
                                                    <?php echo h($company); ?>
                                                </div>

                                            <?php endif; ?>

                                        </div>

                                    </div>

                                </td>

                                <!-- CONTENT -->

                                <td>

                                    <div class="content-preview">
                                        <?php echo h($content); ?>
                                    </div>

                                </td>

                                <!-- RATING -->

                                <td>

                                    <?php if ($rating !== null): ?>

                                        <div class="rating">

                                            <?php

                                            $fullStars = (int)floor($rating);

                                            $hasHalf =
                                                ($rating - $fullStars) >= 0.5;

                                            for ($star = 1; $star <= 5; $star++):
                                            ?>

                                                <?php if ($star <= $fullStars): ?>

                                                    <i class="fa-solid fa-star"></i>

                                                <?php elseif (
                                                    $star === $fullStars + 1
                                                    && $hasHalf
                                                ): ?>

                                                    <i class="fa-solid fa-star-half-stroke"></i>

                                                <?php else: ?>

                                                    <i class="fa-regular fa-star"></i>

                                                <?php endif; ?>

                                            <?php endfor; ?>

                                            <span class="rating-number">
                                                <?php echo h(number_format($rating, 1)); ?>
                                            </span>

                                        </div>

                                    <?php else: ?>

                                        <span class="muted">
                                            Not rated
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- STATUS -->

                                <td>

                                    <form
                                        method="POST"
                                        class="inline-form"
                                    >

                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?php echo h($csrfToken); ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_status"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?php echo (int)$testimonial['id']; ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="badge <?php echo (int)$testimonial['status'] === 1
                                                ? 'badge-active'
                                                : 'badge-inactive'; ?>"
                                            title="Click to change status"
                                            style="border:0;"
                                        >

                                            <i class="fa-solid fa-circle"></i>

                                            <?php echo (int)$testimonial['status'] === 1
                                                ? 'Active'
                                                : 'Inactive'; ?>

                                        </button>

                                    </form>

                                </td>

                                <!-- FEATURED -->

                                <td>

                                    <form
                                        method="POST"
                                        class="inline-form"
                                    >

                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?php echo h($csrfToken); ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_featured"
                                        >

                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?php echo (int)$testimonial['id']; ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="badge <?php echo (int)$testimonial['featured'] === 1
                                                ? 'badge-featured'
                                                : 'badge-normal'; ?>"
                                            title="Click to change featured status"
                                            style="border:0;"
                                        >

                                            <i class="fa-solid fa-star"></i>

                                            <?php echo (int)$testimonial['featured'] === 1
                                                ? 'Featured'
                                                : 'Normal'; ?>

                                        </button>

                                    </form>

                                </td>

                                <!-- SORT -->

                                <td>

                                    <span class="badge badge-normal">
                                        <?php echo (int)$testimonial['sort_order']; ?>
                                    </span>

                                </td>

                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">

                                        <a
                                            href="?edit=<?php echo (int)$testimonial['id']; ?>"
                                            class="icon-btn"
                                            title="Edit"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>

                                        <button
                                            type="button"
                                            class="icon-btn danger"
                                            title="Delete"
                                            onclick="deleteTestimonial(
                                                <?php echo (int)$testimonial['id']; ?>,
                                                '<?php echo h(addslashes($name)); ?>'
                                            )"
                                        >
                                            <i class="fa-solid fa-trash"></i>
                                        </button>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                <?php endif; ?>

            </div>

            <!-- PAGINATION -->

            <?php if ($totalPages > 1): ?>

                <div class="pagination">

                    <div class="pagination-info">

                        Showing
                        <strong>
                            <?php echo $totalRows > 0
                                ? $offset + 1
                                : 0; ?>
                        </strong>

                        –
                        <strong>
                            <?php echo min(
                                $offset + $perPage,
                                $totalRows
                            ); ?>
                        </strong>

                        of
                        <strong>
                            <?php echo $totalRows; ?>
                        </strong>

                    </div>

                    <div class="pagination-links">

                        <a
                            href="<?php echo $page > 1
                                ? h(pageUrl($page - 1))
                                : '#'; ?>"
                            class="page-link <?php echo $page <= 1
                                ? 'disabled'
                                : ''; ?>"
                        >
                            <i class="fa-solid fa-chevron-left"></i>
                        </a>

                        <?php

                        $startPage = max(
                            1,
                            $page - 2
                        );

                        $endPage = min(
                            $totalPages,
                            $page + 2
                        );

                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):
                        ?>

                            <a
                                href="<?php echo h(pageUrl($p)); ?>"
                                class="page-link <?php echo $p === $page
                                    ? 'active'
                                    : ''; ?>"
                            >
                                <?php echo $p; ?>
                            </a>

                        <?php endfor; ?>

                        <a
                            href="<?php echo $page < $totalPages
                                ? h(pageUrl($page + 1))
                                : '#'; ?>"
                            class="page-link <?php echo $page >= $totalPages
                                ? 'disabled'
                                : ''; ?>"
                        >
                            <i class="fa-solid fa-chevron-right"></i>
                        </a>

                    </div>

                </div>

            <?php endif; ?>

        </section>

    </main>

</div>

<!-- =========================================================
     ADD / EDIT MODAL
========================================================== -->

<div
    class="modal-backdrop <?php echo $editTestimonial ? 'show' : ''; ?>"
    id="testimonialModal"
>

    <div class="modal">

        <form
            method="POST"
            action=""
            enctype="multipart/form-data"
        >

            <input
                type="hidden"
                name="csrf_token"
                value="<?php echo h($csrfToken); ?>"
            >

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                value="<?php echo (int)$formData['id']; ?>"
            >

            <div class="modal-header">

                <div>

                    <div class="modal-title">

                        <?php echo $formData['id'] > 0
                            ? 'Edit Testimonial'
                            : 'Add Testimonial'; ?>

                    </div>

                    <div class="modal-subtitle">
                        Add authentic customer feedback
                        for your website.
                    </div>

                </div>

                <button
                    type="button"
                    class="modal-close"
                    onclick="closeTestimonialModal()"
                >
                    <i class="fa-solid fa-xmark"></i>
                </button>

            </div>

            <div class="modal-body">

                <div class="form-grid">

                    <!-- NAME -->

                    <div class="form-group">

                        <label class="form-label">
                            Customer Name
                            <span class="required">*</span>
                        </label>

                        <input
                            type="text"
                            name="name"
                            class="form-control"
                            maxlength="255"
                            required
                            value="<?php echo h($formData['name']); ?>"
                            placeholder="Enter customer name"
                        >

                    </div>

                    <!-- DESIGNATION -->

                    <div class="form-group">

                        <label class="form-label">
                            Designation
                        </label>

                        <input
                            type="text"
                            name="designation"
                            class="form-control"
                            maxlength="255"
                            value="<?php echo h($formData['designation']); ?>"
                            placeholder="e.g. Managing Director"
                        >

                    </div>

                    <!-- COMPANY -->

                    <div class="form-group">

                        <label class="form-label">
                            Company
                        </label>

                        <input
                            type="text"
                            name="company"
                            class="form-control"
                            maxlength="255"
                            value="<?php echo h($formData['company']); ?>"
                            placeholder="e.g. ABC Chemicals Pvt. Ltd."
                        >

                    </div>

                    <!-- TESTIMONIAL IMAGE: MEDIA LIBRARY OR DIRECT UPLOAD -->

                    <div class="form-group full">
                        <label class="form-label">Customer Image</label>
                        <select name="image_id" id="testimonialImageId" class="form-select">
                            <option value="">No image selected</option>
                            <?php foreach ($mediaImages as $mediaImage): ?>
                                <option value="<?php echo (int)$mediaImage['id']; ?>"
                                    <?php echo (string)$formData['image_id'] === (string)$mediaImage['id'] ? 'selected' : ''; ?>>
                                    #<?php echo (int)$mediaImage['id']; ?> — <?php echo h($mediaImage['title'] ?: $mediaImage['original_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-help">Choose an existing image from the Media Library, or upload a new image below.</div>
                        <?php if (!empty($formData['image_id']) && isset($mediaById[(int)$formData['image_id']])): ?>
                            <div style="margin-top:10px;display:flex;align-items:center;gap:12px;">
                                <img src="../<?php echo h(ltrim((string)$mediaById[(int)$formData['image_id']]['file_path'], '/')); ?>" alt="Current customer image" style="width:58px;height:58px;object-fit:cover;border-radius:12px;border:1px solid var(--border);">
                                <span class="form-help">Current selected image</span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="form-group full">
                        <label class="form-label">Upload New Image</label>
                        <input type="file" name="testimonial_image" id="testimonialImageUpload" class="form-control" accept="image/jpeg,image/png,image/gif,image/webp">
                        <div class="form-help">JPG, PNG, GIF or WEBP. Maximum 8 MB. The uploaded image is added to the existing media table automatically.</div>
                    </div>

                    <!-- RATING -->

                    <div class="form-group">

                        <label class="form-label">
                            Rating
                        </label>

                        <input
                            type="number"
                            name="rating"
                            class="form-control"
                            min="0"
                            max="5"
                            step="0.01"
                            value="<?php echo h($formData['rating']); ?>"
                            placeholder="0.00 - 5.00"
                        >

                        <div class="form-help">
                            Example: 5, 4.5, 4.75
                        </div>

                    </div>

                    <!-- SORT ORDER -->

                    <div class="form-group">

                        <label class="form-label">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            min="0"
                            step="1"
                            value="<?php echo h($formData['sort_order']); ?>"
                            placeholder="0"
                        >

                        <div class="form-help">
                            Lower number appears earlier.
                        </div>

                    </div>

                    <!-- CONTENT -->

                    <div class="form-group full">

                        <label class="form-label">
                            Testimonial Content
                            <span class="required">*</span>
                        </label>

                        <textarea
                            name="content"
                            class="form-textarea"
                            required
                            placeholder="Write the customer's testimonial..."
                        ><?php echo h($formData['content']); ?></textarea>

                    </div>

                    <!-- STATUS / FEATURED -->

                    <div class="form-group full">

                        <label class="form-label">
                            Publishing
                        </label>

                        <div class="switch-row">

                            <label class="switch-box">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    <?php echo (int)$formData['status'] === 1
                                        ? 'checked'
                                        : ''; ?>
                                >

                                <span class="switch-text">
                                    Active
                                </span>

                            </label>

                            <label class="switch-box">

                                <input
                                    type="checkbox"
                                    name="featured"
                                    value="1"
                                    <?php echo (int)$formData['featured'] === 1
                                        ? 'checked'
                                        : ''; ?>
                                >

                                <span class="switch-text">
                                    Featured
                                </span>

                            </label>

                        </div>

                    </div>

                </div>

            </div>

            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeTestimonialModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid fa-check"></i>

                    <?php echo $formData['id'] > 0
                        ? 'Update Testimonial'
                        : 'Save Testimonial'; ?>

                </button>

            </div>

        </form>

    </div>

</div>

<!-- =========================================================
     DELETE FORM
========================================================== -->

<form
    method="POST"
    id="deleteForm"
    style="display:none;"
>

    <input
        type="hidden"
        name="csrf_token"
        value="<?php echo h($csrfToken); ?>"
    >

    <input
        type="hidden"
        name="action"
        value="delete"
    >

    <input
        type="hidden"
        name="id"
        id="deleteId"
        value=""
    >

</form>

<script>

    const testimonialImageId = document.getElementById('testimonialImageId');
    const testimonialImageUpload = document.getElementById('testimonialImageUpload');
    testimonialImageUpload?.addEventListener('change', function () {
        if (this.files && this.files.length && testimonialImageId) testimonialImageId.value = '';
    });
    testimonialImageId?.addEventListener('change', function () {
        if (this.value && testimonialImageUpload) testimonialImageUpload.value = '';
    });

    function openTestimonialModal() {

        const modal =
            document.getElementById('testimonialModal');

        if (!modal) {
            return;
        }

        /*
         * New record should open clean modal.
         * Existing edit URL automatically opens on page load.
         */
        window.history.replaceState(
            {},
            document.title,
            window.location.pathname
        );

        modal.classList.add('show');

        document.body.style.overflow = 'hidden';
    }


    function closeTestimonialModal() {

        const modal =
            document.getElementById('testimonialModal');

        if (!modal) {
            return;
        }

        modal.classList.remove('show');

        document.body.style.overflow = '';

        /*
         * If edit mode was opened using ?edit=ID,
         * return to clean testimonials URL.
         */
        const cleanUrl =
            window.location.pathname;

        window.history.replaceState(
            {},
            document.title,
            cleanUrl
        );

        /*
         * Redirect only if this was edit mode,
         * so refresh doesn't keep modal open.
         */
        if (
            new URLSearchParams(window.location.search)
                .has('edit')
        ) {
            window.location.href =
                window.location.pathname;
        }
    }


    function deleteTestimonial(id, name) {

        const message =
            'Delete testimonial "' +
            name +
            '"?\n\nThis action cannot be undone.';

        if (!window.confirm(message)) {
            return;
        }

        const idInput =
            document.getElementById('deleteId');

        const form =
            document.getElementById('deleteForm');

        if (!idInput || !form) {
            return;
        }

        idInput.value = id;

        form.submit();
    }


    document.addEventListener(
        'keydown',
        function(event) {

            if (event.key !== 'Escape') {
                return;
            }

            const modal =
                document.getElementById('testimonialModal');

            if (
                modal &&
                modal.classList.contains('show')
            ) {
                closeTestimonialModal();
            }

        }
    );


    document
        .getElementById('testimonialModal')
        ?.addEventListener(
            'click',
            function(event) {

                if (event.target === this) {
                    closeTestimonialModal();
                }

            }
        );


    /*
     * If edit mode is active, lock body scroll.
     */
    <?php if ($editTestimonial): ?>

        document.body.style.overflow = 'hidden';

    <?php endif; ?>

</script>

</body>
</html>