<?php
/**
 * Pure Chemical - Industries Management
 * File: admin/industries.php
 *
 * Uses existing table:
 * industries
 *
 * No new table.
 * No duplicate data.
 */

ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* ---------------------------------------------------------
   DATABASE
--------------------------------------------------------- */
$dbLoaded = false;

$possibleDbFiles = [
    __DIR__ . '/includes/db.php',
    __DIR__ . '/db.php',
];

foreach ($possibleDbFiles as $dbFile) {
    if (file_exists($dbFile)) {
        require_once $dbFile;
        $dbLoaded = true;
        break;
    }
}

if (!$dbLoaded || !isset($pdo) || !($pdo instanceof PDO)) {
    ob_end_clean();
    exit('Database connection not available.');
}

/* ---------------------------------------------------------
   AUTH
--------------------------------------------------------- */
$authFile = __DIR__ . '/includes/auth.php';

if (file_exists($authFile)) {
    require_once $authFile;
}

if (function_exists('requireAdmin')) {
    requireAdmin();
} else {
    $loggedIn =
        !empty($_SESSION['admin_id']) ||
        !empty($_SESSION['admin_logged_in']);

    if (!$loggedIn) {
        header('Location: login.php');
        exit;
    }
}

/* ---------------------------------------------------------
   FUNCTIONS
--------------------------------------------------------- */
$functionsFile = __DIR__ . '/includes/functions.php';

if (file_exists($functionsFile)) {
    require_once $functionsFile;
}

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/* ---------------------------------------------------------
   CSRF
--------------------------------------------------------- */
$csrfFile = __DIR__ . '/includes/csrf.php';

if (file_exists($csrfFile)) {
    require_once $csrfFile;
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('verify_csrf')) {
    function verify_csrf($token)
    {
        return !empty($token)
            && !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $token);
    }
}

/* ---------------------------------------------------------
   PAGE SETTINGS
--------------------------------------------------------- */
$page_title = 'Industries';
$active_menu = 'industries';

$message = '';
$messageType = '';

/* ---------------------------------------------------------
   DELETE INDUSTRY
--------------------------------------------------------- */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'delete'
) {
    $token = $_POST['csrf_token'] ?? '';

    if (!verify_csrf($token)) {
        $message = 'Security verification failed. Please try again.';
        $messageType = 'error';
    } else {
        $industryId = (int)($_POST['industry_id'] ?? 0);

        if ($industryId <= 0) {
            $message = 'Invalid industry selected.';
            $messageType = 'error';
        } else {
            try {
                /*
                 * First check child industries.
                 */
                $childStmt = $pdo->prepare("
                    SELECT COUNT(*)
                    FROM industries
                    WHERE parent_id = ?
                ");

                $childStmt->execute([$industryId]);
                $childCount = (int)$childStmt->fetchColumn();

                if ($childCount > 0) {
                    $message =
                        'This industry cannot be deleted because it has ' .
                        $childCount .
                        ' child industry/industries. Move or delete the child industries first.';

                    $messageType = 'error';
                } else {
                    /*
                     * Check industry exists.
                     */
                    $checkStmt = $pdo->prepare("
                        SELECT id, name
                        FROM industries
                        WHERE id = ?
                        LIMIT 1
                    ");

                    $checkStmt->execute([$industryId]);
                    $industry = $checkStmt->fetch();

                    if (!$industry) {
                        $message = 'Industry not found.';
                        $messageType = 'error';
                    } else {
                        $deleteStmt = $pdo->prepare("
                            DELETE FROM industries
                            WHERE id = ?
                            LIMIT 1
                        ");

                        $deleteStmt->execute([$industryId]);

                        $message =
                            'Industry "' .
                            $industry['name'] .
                            '" deleted successfully.';

                        $messageType = 'success';
                    }
                }
            } catch (PDOException $e) {
                error_log(
                    'Industry Delete Error: ' .
                    $e->getMessage()
                );

                $message = 'Unable to delete the industry.';
                $messageType = 'error';
            }
        }
    }
}

/* ---------------------------------------------------------
   TOGGLE STATUS
--------------------------------------------------------- */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'toggle_status'
) {
    $token = $_POST['csrf_token'] ?? '';

    if (!verify_csrf($token)) {
        $message = 'Security verification failed.';
        $messageType = 'error';
    } else {
        $industryId = (int)($_POST['industry_id'] ?? 0);

        if ($industryId > 0) {
            try {
                $stmt = $pdo->prepare("
                    SELECT status
                    FROM industries
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$industryId]);
                $currentStatus = $stmt->fetchColumn();

                if ($currentStatus === false) {
                    $message = 'Industry not found.';
                    $messageType = 'error';
                } else {
                    $newStatus = ((int)$currentStatus === 1) ? 0 : 1;

                    $update = $pdo->prepare("
                        UPDATE industries
                        SET status = ?
                        WHERE id = ?
                    ");

                    $update->execute([
                        $newStatus,
                        $industryId
                    ]);

                    $message =
                        $newStatus === 1
                            ? 'Industry activated successfully.'
                            : 'Industry deactivated successfully.';

                    $messageType = 'success';
                }
            } catch (PDOException $e) {
                error_log(
                    'Industry Status Error: ' .
                    $e->getMessage()
                );

                $message = 'Unable to update industry status.';
                $messageType = 'error';
            }
        }
    }
}

/* ---------------------------------------------------------
   TOGGLE FEATURED
--------------------------------------------------------- */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'toggle_featured'
) {
    $token = $_POST['csrf_token'] ?? '';

    if (!verify_csrf($token)) {
        $message = 'Security verification failed.';
        $messageType = 'error';
    } else {
        $industryId = (int)($_POST['industry_id'] ?? 0);

        if ($industryId > 0) {
            try {
                $stmt = $pdo->prepare("
                    SELECT featured
                    FROM industries
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$industryId]);
                $currentFeatured = $stmt->fetchColumn();

                if ($currentFeatured === false) {
                    $message = 'Industry not found.';
                    $messageType = 'error';
                } else {
                    $newFeatured =
                        ((int)$currentFeatured === 1) ? 0 : 1;

                    $update = $pdo->prepare("
                        UPDATE industries
                        SET featured = ?
                        WHERE id = ?
                    ");

                    $update->execute([
                        $newFeatured,
                        $industryId
                    ]);

                    $message =
                        $newFeatured === 1
                            ? 'Industry marked as featured.'
                            : 'Industry removed from featured.';

                    $messageType = 'success';
                }
            } catch (PDOException $e) {
                error_log(
                    'Industry Featured Error: ' .
                    $e->getMessage()
                );

                $message = 'Unable to update featured status.';
                $messageType = 'error';
            }
        }
    }
}

/* ---------------------------------------------------------
   FILTERS
--------------------------------------------------------- */
$search = trim($_GET['search'] ?? '');
$statusFilter = $_GET['status'] ?? '';
$featuredFilter = $_GET['featured'] ?? '';
$parentFilter = isset($_GET['parent_id'])
    ? (int)$_GET['parent_id']
    : 0;

/* ---------------------------------------------------------
   LOAD ALL INDUSTRIES FOR PARENT FILTER / TREE
--------------------------------------------------------- */
try {
    $allStmt = $pdo->query("
        SELECT
            id,
            parent_id,
            name,
            slug,
            status,
            featured,
            sort_order
        FROM industries
        ORDER BY
            parent_id IS NOT NULL,
            sort_order ASC,
            name ASC
    ");

    $allIndustries = $allStmt->fetchAll();

} catch (PDOException $e) {
    error_log(
        'Industry Parent Load Error: ' .
        $e->getMessage()
    );

    $allIndustries = [];
}

/* ---------------------------------------------------------
   BUILD PARENT MAP
--------------------------------------------------------- */
$industryMap = [];

foreach ($allIndustries as $industry) {
    $industryMap[(int)$industry['id']] = $industry;
}

/* ---------------------------------------------------------
   BUILD TREE LEVELS
--------------------------------------------------------- */
$childrenMap = [];

foreach ($allIndustries as $industry) {
    $parentId = !empty($industry['parent_id'])
        ? (int)$industry['parent_id']
        : 0;

    if (!isset($childrenMap[$parentId])) {
        $childrenMap[$parentId] = [];
    }

    $childrenMap[$parentId][] = $industry;
}

/**
 * Create hierarchy label.
 */
function industryParentPath(
    $industryId,
    $industryMap
) {
    $parts = [];
    $currentId = (int)$industryId;
    $guard = 0;

    while (
        isset($industryMap[$currentId]) &&
        $guard < 50
    ) {
        $parentId = !empty(
            $industryMap[$currentId]['parent_id']
        )
            ? (int)$industryMap[$currentId]['parent_id']
            : 0;

        if ($parentId <= 0) {
            break;
        }

        if (!isset($industryMap[$parentId])) {
            break;
        }

        array_unshift(
            $parts,
            $industryMap[$parentId]['name']
        );

        $currentId = $parentId;
        $guard++;
    }

    return $parts;
}

/* ---------------------------------------------------------
   STATS
--------------------------------------------------------- */
try {
    $totalIndustries = (int)$pdo->query("
        SELECT COUNT(*)
        FROM industries
    ")->fetchColumn();

    $activeIndustries = (int)$pdo->query("
        SELECT COUNT(*)
        FROM industries
        WHERE status = 1
    ")->fetchColumn();

    $featuredIndustries = (int)$pdo->query("
        SELECT COUNT(*)
        FROM industries
        WHERE featured = 1
    ")->fetchColumn();

    $childIndustries = (int)$pdo->query("
        SELECT COUNT(*)
        FROM industries
        WHERE parent_id IS NOT NULL
    ")->fetchColumn();

} catch (PDOException $e) {
    $totalIndustries = 0;
    $activeIndustries = 0;
    $featuredIndustries = 0;
    $childIndustries = 0;
}

/* ---------------------------------------------------------
   PAGINATION
--------------------------------------------------------- */
$perPage = 12;

$page = isset($_GET['page'])
    ? max(1, (int)$_GET['page'])
    : 1;

/* ---------------------------------------------------------
   WHERE
--------------------------------------------------------- */
$where = [];
$params = [];

if ($search !== '') {
    $where[] = "
        (
            i.name LIKE ?
            OR i.slug LIKE ?
            OR i.short_description LIKE ?
        )
    ";

    $searchLike = '%' . $search . '%';

    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

if ($statusFilter !== '') {
    $where[] = "i.status = ?";
    $params[] = ((int)$statusFilter === 1) ? 1 : 0;
}

if ($featuredFilter !== '') {
    $where[] = "i.featured = ?";
    $params[] = ((int)$featuredFilter === 1) ? 1 : 0;
}

if ($parentFilter > 0) {
    $where[] = "i.parent_id = ?";
    $params[] = $parentFilter;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/* ---------------------------------------------------------
   TOTAL FILTERED
--------------------------------------------------------- */
try {
    $countStmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM industries i
        $whereSql
    ");

    $countStmt->execute($params);

    $filteredTotal = (int)$countStmt->fetchColumn();

} catch (PDOException $e) {
    error_log(
        'Industry Count Error: ' .
        $e->getMessage()
    );

    $filteredTotal = 0;
}

$totalPages = max(
    1,
    (int)ceil($filteredTotal / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

/* ---------------------------------------------------------
   LOAD INDUSTRIES
--------------------------------------------------------- */
try {
    $sql = "
        SELECT
            i.id,
            i.parent_id,
            i.name,
            i.slug,
            i.short_description,
            i.description,
            i.banner_id,
            i.featured_image_id,
            i.status,
            i.featured,
            i.sort_order,
            i.created_at,
            i.updated_at
        FROM industries i
        $whereSql
        ORDER BY
            COALESCE(i.parent_id, 0) ASC,
            i.sort_order ASC,
            i.name ASC
        LIMIT $perPage OFFSET $offset
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $industries = $stmt->fetchAll();

} catch (PDOException $e) {
    error_log(
        'Industry Listing Error: ' .
        $e->getMessage()
    );

    $industries = [];

    $message = 'Unable to load industries.';
    $messageType = 'error';
}

/* ---------------------------------------------------------
   URL HELPER
--------------------------------------------------------- */
function industryQueryUrl($overrides = [])
{
    $query = $_GET;

    foreach ($overrides as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

    return '?' . http_build_query($query);
}

/* ---------------------------------------------------------
   HEADER
--------------------------------------------------------- */
$headerLoaded = false;

$headerFiles = [
    __DIR__ . '/includes/header.php',
    __DIR__ . '/header.php',
];

foreach ($headerFiles as $headerFile) {
    if (file_exists($headerFile)) {
        require_once $headerFile;
        $headerLoaded = true;
        break;
    }
}

if (!$headerLoaded) {
    ob_end_clean();

    exit(
        'Admin header not found. Please keep header.php or includes/header.php available.'
    );
}
?>

<style>
/* =========================================================
   INDUSTRIES PAGE
========================================================= */

.industries-page {
    width: 100%;
    max-width: 1600px;
    margin: 0 auto;
    padding: 8px 0 40px;
}

.industries-hero {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    gap: 24px;
    margin-bottom: 24px;
}

.industries-title-wrap {
    min-width: 0;
}

.industries-eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 7px 11px;
    border-radius: 999px;
    background: rgba(37, 99, 235, .08);
    color: #2563eb;
    font-size: 11px;
    font-weight: 800;
    letter-spacing: .08em;
    text-transform: uppercase;
    margin-bottom: 10px;
}

.industries-eyebrow i {
    font-size: 12px;
}

.industries-title {
    margin: 0;
    color: #0f172a;
    font-size: clamp(26px, 3vw, 38px);
    line-height: 1.1;
    font-weight: 850;
    letter-spacing: -.035em;
}

.industries-subtitle {
    margin: 9px 0 0;
    color: #64748b;
    font-size: 14px;
    line-height: 1.65;
}

.industry-primary-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 9px;
    min-height: 46px;
    padding: 0 18px;
    border: 0;
    border-radius: 13px;
    background: #111827;
    color: #fff;
    text-decoration: none;
    font-size: 13px;
    font-weight: 800;
    box-shadow: 0 12px 25px rgba(15, 23, 42, .12);
    transition: .2s ease;
    white-space: nowrap;
}

.industry-primary-btn:hover {
    color: #fff;
    transform: translateY(-1px);
    box-shadow: 0 16px 30px rgba(15, 23, 42, .17);
}

/* ---------------------------------------------------------
   ALERT
--------------------------------------------------------- */

.industry-alert {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 14px 16px;
    margin-bottom: 20px;
    border: 1px solid;
    border-radius: 14px;
    font-size: 13px;
    line-height: 1.55;
}

.industry-alert i {
    margin-top: 2px;
}

.industry-alert.success {
    background: #f0fdf4;
    border-color: #bbf7d0;
    color: #166534;
}

.industry-alert.error {
    background: #fef2f2;
    border-color: #fecaca;
    color: #991b1b;
}

/* ---------------------------------------------------------
   STATS
--------------------------------------------------------- */

.industry-stats {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 14px;
    margin-bottom: 20px;
}

.industry-stat {
    position: relative;
    overflow: hidden;
    padding: 18px;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0 8px 28px rgba(15, 23, 42, .045);
}

.industry-stat::after {
    content: "";
    position: absolute;
    width: 90px;
    height: 90px;
    right: -35px;
    top: -35px;
    border-radius: 50%;
    background: rgba(37, 99, 235, .06);
}

.industry-stat-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.industry-stat-icon {
    width: 42px;
    height: 42px;
    display: grid;
    place-items: center;
    border-radius: 13px;
    background: #f8fafc;
    color: #2563eb;
    font-size: 17px;
}

.industry-stat-value {
    margin-top: 13px;
    color: #0f172a;
    font-size: 26px;
    line-height: 1;
    font-weight: 850;
    letter-spacing: -.03em;
}

.industry-stat-label {
    margin-top: 7px;
    color: #64748b;
    font-size: 12px;
    font-weight: 650;
}

/* ---------------------------------------------------------
   FILTER CARD
--------------------------------------------------------- */

.industry-filter-card {
    margin-bottom: 20px;
    padding: 16px;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0 8px 28px rgba(15, 23, 42, .045);
}

.industry-filter-form {
    display: grid;
    grid-template-columns: minmax(220px, 1.7fr) minmax(150px, 1fr) minmax(150px, 1fr) minmax(150px, 1fr) auto auto;
    gap: 10px;
    align-items: center;
}

.industry-input,
.industry-select {
    width: 100%;
    height: 44px;
    padding: 0 13px;
    border: 1px solid #e2e8f0;
    border-radius: 11px;
    background: #f8fafc;
    color: #0f172a;
    outline: none;
    font-size: 13px;
    transition: .2s ease;
}

.industry-input:focus,
.industry-select:focus {
    border-color: #93c5fd;
    background: #fff;
    box-shadow: 0 0 0 4px rgba(37, 99, 235, .08);
}

.industry-search-wrap {
    position: relative;
}

.industry-search-wrap i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    pointer-events: none;
}

.industry-search-wrap .industry-input {
    padding-left: 39px;
}

.industry-filter-btn,
.industry-reset-btn {
    height: 44px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 0 15px;
    border-radius: 11px;
    text-decoration: none;
    font-size: 12px;
    font-weight: 800;
    transition: .2s ease;
    white-space: nowrap;
}

.industry-filter-btn {
    border: 1px solid #111827;
    background: #111827;
    color: #fff;
    cursor: pointer;
}

.industry-filter-btn:hover {
    background: #020617;
    color: #fff;
}

.industry-reset-btn {
    border: 1px solid #e2e8f0;
    background: #fff;
    color: #475569;
}

.industry-reset-btn:hover {
    border-color: #cbd5e1;
    color: #0f172a;
}

/* ---------------------------------------------------------
   TABLE
--------------------------------------------------------- */

.industry-table-card {
    overflow: hidden;
    border: 1px solid #e5e7eb;
    border-radius: 20px;
    background: #fff;
    box-shadow: 0 8px 28px rgba(15, 23, 42, .045);
}

.industry-table-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
    padding: 17px 20px;
    border-bottom: 1px solid #eef2f7;
}

.industry-table-heading {
    margin: 0;
    color: #0f172a;
    font-size: 15px;
    font-weight: 850;
}

.industry-result-count {
    color: #64748b;
    font-size: 12px;
    font-weight: 650;
}

.industry-table-wrap {
    width: 100%;
    overflow-x: auto;
}

.industry-table {
    width: 100%;
    min-width: 1050px;
    border-collapse: collapse;
}

.industry-table th {
    padding: 13px 16px;
    background: #f8fafc;
    color: #64748b;
    border-bottom: 1px solid #e5e7eb;
    font-size: 10px;
    font-weight: 850;
    letter-spacing: .07em;
    text-transform: uppercase;
    white-space: nowrap;
}

.industry-table td {
    padding: 14px 16px;
    color: #334155;
    border-bottom: 1px solid #f1f5f9;
    font-size: 13px;
    vertical-align: middle;
}

.industry-table tbody tr {
    transition: .16s ease;
}

.industry-table tbody tr:hover {
    background: #fafcff;
}

.industry-table tbody tr:last-child td {
    border-bottom: 0;
}

.industry-check {
    width: 16px;
    height: 16px;
    accent-color: #2563eb;
}

.industry-id {
    color: #94a3b8;
    font-weight: 700;
    font-size: 11px;
}

.industry-name-cell {
    display: flex;
    align-items: center;
    gap: 11px;
    min-width: 240px;
}

.industry-avatar {
    width: 40px;
    height: 40px;
    flex: 0 0 40px;
    display: grid;
    place-items: center;
    border-radius: 12px;
    background: #eff6ff;
    color: #2563eb;
    font-size: 15px;
    font-weight: 850;
}

.industry-name {
    color: #0f172a;
    font-size: 13px;
    font-weight: 800;
}

.industry-slug {
    margin-top: 3px;
    color: #94a3b8;
    font-size: 11px;
}

.industry-parent {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    max-width: 210px;
    color: #64748b;
    font-size: 11px;
    font-weight: 650;
}

.industry-parent i {
    color: #cbd5e1;
}

.industry-description {
    max-width: 300px;
    color: #64748b;
    line-height: 1.5;
    font-size: 12px;
}

.industry-id-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 8px;
    border-radius: 8px;
    background: #f8fafc;
    color: #64748b;
    font-size: 10px;
    font-weight: 800;
}

.industry-status,
.industry-featured {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 9px;
    border-radius: 999px;
    border: 0;
    font-size: 10px;
    font-weight: 850;
    cursor: pointer;
    transition: .18s ease;
}

.industry-status.active {
    background: #ecfdf5;
    color: #047857;
}

.industry-status.inactive {
    background: #fef2f2;
    color: #b91c1c;
}

.industry-featured.yes {
    background: #fffbeb;
    color: #b45309;
}

.industry-featured.no {
    background: #f8fafc;
    color: #94a3b8;
}

.industry-status:hover,
.industry-featured:hover {
    transform: translateY(-1px);
}

.industry-media-cell {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}

.industry-media-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 7px;
    border-radius: 7px;
    background: #f8fafc;
    color: #64748b;
    font-size: 9px;
    font-weight: 800;
}

.industry-actions {
    display: flex;
    align-items: center;
    gap: 6px;
}

.industry-action {
    width: 34px;
    height: 34px;
    display: grid;
    place-items: center;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    background: #fff;
    color: #64748b;
    text-decoration: none;
    cursor: pointer;
    transition: .18s ease;
}

.industry-action:hover {
    border-color: #cbd5e1;
    color: #0f172a;
    background: #f8fafc;
}

.industry-action.delete:hover {
    border-color: #fecaca;
    background: #fef2f2;
    color: #dc2626;
}

.industry-action.edit:hover {
    border-color: #bfdbfe;
    background: #eff6ff;
    color: #2563eb;
}

/* ---------------------------------------------------------
   EMPTY
--------------------------------------------------------- */

.industry-empty {
    padding: 70px 20px;
    text-align: center;
}

.industry-empty-icon {
    width: 64px;
    height: 64px;
    display: grid;
    place-items: center;
    margin: 0 auto 14px;
    border-radius: 18px;
    background: #f8fafc;
    color: #94a3b8;
    font-size: 25px;
}

.industry-empty h3 {
    margin: 0;
    color: #0f172a;
    font-size: 17px;
    font-weight: 850;
}

.industry-empty p {
    max-width: 460px;
    margin: 8px auto 18px;
    color: #64748b;
    font-size: 13px;
    line-height: 1.6;
}

/* ---------------------------------------------------------
   PAGINATION
--------------------------------------------------------- */

.industry-pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
    padding: 16px 20px;
    border-top: 1px solid #eef2f7;
}

.industry-pagination-info {
    color: #64748b;
    font-size: 12px;
}

.industry-pagination-links {
    display: flex;
    align-items: center;
    gap: 5px;
}

.industry-page-link {
    min-width: 34px;
    height: 34px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0 9px;
    border: 1px solid #e2e8f0;
    border-radius: 9px;
    background: #fff;
    color: #64748b;
    text-decoration: none;
    font-size: 11px;
    font-weight: 800;
}

.industry-page-link:hover,
.industry-page-link.current {
    border-color: #111827;
    background: #111827;
    color: #fff;
}

.industry-page-dots {
    color: #94a3b8;
    padding: 0 3px;
}

/* ---------------------------------------------------------
   RESPONSIVE
--------------------------------------------------------- */

@media (max-width: 1250px) {
    .industry-filter-form {
        grid-template-columns:
            minmax(200px, 1fr)
            minmax(150px, 1fr)
            minmax(150px, 1fr);
    }
}

@media (max-width: 1050px) {
    .industry-stats {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .industries-hero {
        align-items: flex-start;
        flex-direction: column;
    }
}

@media (max-width: 720px) {
    .industries-page {
        padding-bottom: 25px;
    }

    .industry-stats {
        grid-template-columns: 1fr;
    }

    .industry-filter-form {
        grid-template-columns: 1fr;
    }

    .industry-table-head,
    .industry-pagination {
        align-items: flex-start;
        flex-direction: column;
    }

    .industry-pagination-links {
        flex-wrap: wrap;
    }

    .industry-primary-btn {
        width: 100%;
    }
}
</style>

<div class="industries-page">

    <!-- =====================================================
         HERO
    ====================================================== -->
    <div class="industries-hero">

        <div class="industries-title-wrap">

            <div class="industries-eyebrow">
                <i class="fa-solid fa-industry"></i>
                Industry Management
            </div>

            <h1 class="industries-title">
                Industries
            </h1>

            <p class="industries-subtitle">
                Manage industry pages, hierarchy, featured status,
                visibility and ordering from one place.
            </p>

        </div>

        <a
            href="add_industry.php"
            class="industry-primary-btn"
        >
            <i class="fa-solid fa-plus"></i>
            Add Industry
        </a>

    </div>

    <!-- =====================================================
         ALERT
    ====================================================== -->
    <?php if ($message !== ''): ?>

        <div class="industry-alert <?= e($messageType) ?>">

            <i class="fa-solid
                <?= $messageType === 'success'
                    ? 'fa-circle-check'
                    : 'fa-circle-exclamation'
                ?>"></i>

            <div>
                <?= e($message) ?>
            </div>

        </div>

    <?php endif; ?>

    <!-- =====================================================
         STATS
    ====================================================== -->
    <div class="industry-stats">

        <div class="industry-stat">

            <div class="industry-stat-top">
                <div class="industry-stat-icon">
                    <i class="fa-solid fa-layer-group"></i>
                </div>
            </div>

            <div class="industry-stat-value">
                <?= number_format($totalIndustries) ?>
            </div>

            <div class="industry-stat-label">
                Total Industries
            </div>

        </div>

        <div class="industry-stat">

            <div class="industry-stat-top">
                <div class="industry-stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>
            </div>

            <div class="industry-stat-value">
                <?= number_format($activeIndustries) ?>
            </div>

            <div class="industry-stat-label">
                Active Industries
            </div>

        </div>

        <div class="industry-stat">

            <div class="industry-stat-top">
                <div class="industry-stat-icon">
                    <i class="fa-solid fa-star"></i>
                </div>
            </div>

            <div class="industry-stat-value">
                <?= number_format($featuredIndustries) ?>
            </div>

            <div class="industry-stat-label">
                Featured Industries
            </div>

        </div>

        <div class="industry-stat">

            <div class="industry-stat-top">
                <div class="industry-stat-icon">
                    <i class="fa-solid fa-sitemap"></i>
                </div>
            </div>

            <div class="industry-stat-value">
                <?= number_format($childIndustries) ?>
            </div>

            <div class="industry-stat-label">
                Child Industries
            </div>

        </div>

    </div>

    <!-- =====================================================
         FILTER
    ====================================================== -->
    <div class="industry-filter-card">

        <form
            method="get"
            action="industries.php"
            class="industry-filter-form"
        >

            <div class="industry-search-wrap">

                <i class="fa-solid fa-magnifying-glass"></i>

                <input
                    type="text"
                    name="search"
                    class="industry-input"
                    placeholder="Search industry name, slug..."
                    value="<?= e($search) ?>"
                >

            </div>

            <select
                name="parent_id"
                class="industry-select"
            >

                <option value="">
                    All Parents
                </option>

                <?php foreach ($allIndustries as $parent): ?>

                    <option
                        value="<?= (int)$parent['id'] ?>"
                        <?= $parentFilter === (int)$parent['id']
                            ? 'selected'
                            : ''
                        ?>
                    >
                        <?= e($parent['name']) ?>
                    </option>

                <?php endforeach; ?>

            </select>

            <select
                name="status"
                class="industry-select"
            >

                <option value="">
                    All Status
                </option>

                <option
                    value="1"
                    <?= $statusFilter === '1'
                        ? 'selected'
                        : ''
                    ?>
                >
                    Active
                </option>

                <option
                    value="0"
                    <?= $statusFilter === '0'
                        ? 'selected'
                        : ''
                    ?>
                >
                    Inactive
                </option>

            </select>

            <select
                name="featured"
                class="industry-select"
            >

                <option value="">
                    All Featured
                </option>

                <option
                    value="1"
                    <?= $featuredFilter === '1'
                        ? 'selected'
                        : ''
                    ?>
                >
                    Featured
                </option>

                <option
                    value="0"
                    <?= $featuredFilter === '0'
                        ? 'selected'
                        : ''
                    ?>
                >
                    Not Featured
                </option>

            </select>

            <button
                type="submit"
                class="industry-filter-btn"
            >
                <i class="fa-solid fa-filter"></i>
                Filter
            </button>

            <a
                href="industries.php"
                class="industry-reset-btn"
            >
                <i class="fa-solid fa-rotate-left"></i>
                Reset
            </a>

        </form>

    </div>

    <!-- =====================================================
         TABLE CARD
    ====================================================== -->
    <div class="industry-table-card">

        <div class="industry-table-head">

            <div>
                <h2 class="industry-table-heading">
                    All Industries
                </h2>

                <div class="industry-result-count">
                    <?= number_format($filteredTotal) ?>
                    result<?= $filteredTotal === 1 ? '' : 's' ?>
                    found
                </div>
            </div>

        </div>

        <?php if (!empty($industries)): ?>

            <div class="industry-table-wrap">

                <table class="industry-table">

                    <thead>

                        <tr>

                            <th style="width:40px;">
                                #
                            </th>

                            <th>
                                Industry
                            </th>

                            <th>
                                Parent
                            </th>

                            <th>
                                Description
                            </th>

                            <th>
                                Media
                            </th>

                            <th>
                                Status
                            </th>

                            <th>
                                Featured
                            </th>

                            <th>
                                Order
                            </th>

                            <th>
                                Actions
                            </th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php foreach ($industries as $industry): ?>

                            <?php
                            $industryId = (int)$industry['id'];

                            $parentPath = industryParentPath(
                                $industryId,
                                $industryMap
                            );

                            $shortDescription =
                                trim(
                                    (string)$industry['short_description']
                                );

                            if ($shortDescription === '') {
                                $shortDescription =
                                    trim(
                                        strip_tags(
                                            (string)$industry['description']
                                        )
                                    );
                            }

                            if (
                                mb_strlen(
                                    $shortDescription
                                ) > 105
                            ) {
                                $shortDescription =
                                    mb_substr(
                                        $shortDescription,
                                        0,
                                        105
                                    ) . '...';
                            }
                            ?>

                            <tr>

                                <td>
                                    <span class="industry-id">
                                        <?= $industryId ?>
                                    </span>
                                </td>

                                <!-- INDUSTRY -->
                                <td>

                                    <div class="industry-name-cell">

                                        <div class="industry-avatar">
                                            <i class="fa-solid fa-industry"></i>
                                        </div>

                                        <div>

                                            <div class="industry-name">
                                                <?= e($industry['name']) ?>
                                            </div>

                                            <div class="industry-slug">
                                                /<?= e($industry['slug']) ?>
                                            </div>

                                        </div>

                                    </div>

                                </td>

                                <!-- PARENT -->
                                <td>

                                    <?php if (!empty($parentPath)): ?>

                                        <div
                                            class="industry-parent"
                                            title="<?= e(implode(' / ', $parentPath)) ?>"
                                        >
                                            <i class="fa-solid fa-turn-up"></i>

                                            <?= e(
                                                end($parentPath)
                                            ) ?>
                                        </div>

                                    <?php else: ?>

                                        <span class="industry-id-badge">
                                            <i class="fa-solid fa-house"></i>
                                            Root Industry
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- DESCRIPTION -->
                                <td>

                                    <?php if ($shortDescription !== ''): ?>

                                        <div
                                            class="industry-description"
                                            title="<?= e($shortDescription) ?>"
                                        >
                                            <?= e($shortDescription) ?>
                                        </div>

                                    <?php else: ?>

                                        <span
                                            style="
                                                color:#cbd5e1;
                                                font-size:11px;
                                            "
                                        >
                                            No description
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- MEDIA -->
                                <td>

                                    <div class="industry-media-cell">

                                        <?php if (
                                            !empty(
                                                $industry['featured_image_id']
                                            )
                                        ): ?>

                                            <span
                                                class="industry-media-badge"
                                                title="Featured image ID"
                                            >
                                                <i class="fa-regular fa-image"></i>
                                                F:
                                                <?= (int)$industry[
                                                    'featured_image_id'
                                                ] ?>
                                            </span>

                                        <?php endif; ?>

                                        <?php if (
                                            !empty(
                                                $industry['banner_id']
                                            )
                                        ): ?>

                                            <span
                                                class="industry-media-badge"
                                                title="Banner image ID"
                                            >
                                                <i class="fa-regular fa-images"></i>
                                                B:
                                                <?= (int)$industry[
                                                    'banner_id'
                                                ] ?>
                                            </span>

                                        <?php endif; ?>

                                        <?php if (
                                            empty(
                                                $industry['featured_image_id']
                                            ) &&
                                            empty(
                                                $industry['banner_id']
                                            )
                                        ): ?>

                                            <span
                                                style="
                                                    color:#cbd5e1;
                                                    font-size:11px;
                                                "
                                            >
                                                —
                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>

                                <!-- STATUS -->
                                <td>

                                    <form
                                        method="post"
                                        style="margin:0;"
                                    >

                                        <?= csrf_field() ?>

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_status"
                                        >

                                        <input
                                            type="hidden"
                                            name="industry_id"
                                            value="<?= $industryId ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="industry-status
                                                <?= (int)$industry['status'] === 1
                                                    ? 'active'
                                                    : 'inactive'
                                                ?>"
                                            title="Click to change status"
                                        >

                                            <i class="fa-solid
                                                <?= (int)$industry['status'] === 1
                                                    ? 'fa-circle-check'
                                                    : 'fa-circle-xmark'
                                                ?>"
                                            ></i>

                                            <?= (int)$industry['status'] === 1
                                                ? 'Active'
                                                : 'Inactive'
                                            ?>

                                        </button>

                                    </form>

                                </td>

                                <!-- FEATURED -->
                                <td>

                                    <form
                                        method="post"
                                        style="margin:0;"
                                    >

                                        <?= csrf_field() ?>

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_featured"
                                        >

                                        <input
                                            type="hidden"
                                            name="industry_id"
                                            value="<?= $industryId ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="industry-featured
                                                <?= (int)$industry['featured'] === 1
                                                    ? 'yes'
                                                    : 'no'
                                                ?>"
                                            title="Click to change featured status"
                                        >

                                            <i class="fa-solid fa-star"></i>

                                            <?= (int)$industry['featured'] === 1
                                                ? 'Featured'
                                                : 'No'
                                            ?>

                                        </button>

                                    </form>

                                </td>

                                <!-- ORDER -->
                                <td>

                                    <span class="industry-id-badge">
                                        <i class="fa-solid fa-arrow-down-1-9"></i>

                                        <?= (int)$industry['sort_order'] ?>

                                    </span>

                                </td>

                                <!-- ACTIONS -->
                                <td>

                                    <div class="industry-actions">

                                        <a
                                            href="edit_industry.php?id=<?= $industryId ?>"
                                            class="industry-action edit"
                                            title="Edit Industry"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>

                                        <a
                                            href="industry_images.php?id=<?= $industryId ?>"
                                            class="industry-action"
                                            title="Industry Images"
                                        >
                                            <i class="fa-regular fa-image"></i>
                                        </a>

                                        <a
                                            href="industry_products.php?id=<?= $industryId ?>"
                                            class="industry-action"
                                            title="Industry Products"
                                        >
                                            <i class="fa-solid fa-boxes-stacked"></i>
                                        </a>

                                        <a
                                            href="industry_seo.php?id=<?= $industryId ?>"
                                            class="industry-action"
                                            title="Industry SEO"
                                        >
                                            <i class="fa-solid fa-magnifying-glass-chart"></i>
                                        </a>

                                        <form
                                            method="post"
                                            style="margin:0;"
                                            onsubmit="return confirm(
                                                'Are you sure you want to delete this industry? This action cannot be undone.'
                                            );"
                                        >

                                            <?= csrf_field() ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete"
                                            >

                                            <input
                                                type="hidden"
                                                name="industry_id"
                                                value="<?= $industryId ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="industry-action delete"
                                                title="Delete Industry"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </form>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

            <!-- =================================================
                 PAGINATION
            ================================================== -->
            <?php if ($totalPages > 1): ?>

                <div class="industry-pagination">

                    <div class="industry-pagination-info">

                        Showing
                        <strong>
                            <?= $filteredTotal > 0
                                ? $offset + 1
                                : 0
                            ?>
                        </strong>

                        –
                        <strong>
                            <?= min(
                                $offset + $perPage,
                                $filteredTotal
                            ) ?>
                        </strong>

                        of
                        <strong>
                            <?= number_format($filteredTotal) ?>
                        </strong>

                    </div>

                    <div class="industry-pagination-links">

                        <?php if ($page > 1): ?>

                            <a
                                href="<?= e(
                                    industryQueryUrl([
                                        'page' => $page - 1
                                    ])
                                ) ?>"
                                class="industry-page-link"
                                title="Previous"
                            >
                                <i class="fa-solid fa-chevron-left"></i>
                            </a>

                        <?php endif; ?>

                        <?php
                        $startPage = max(
                            1,
                            $page - 2
                        );

                        $endPage = min(
                            $totalPages,
                            $page + 2
                        );
                        ?>

                        <?php if ($startPage > 1): ?>

                            <a
                                href="<?= e(
                                    industryQueryUrl([
                                        'page' => 1
                                    ])
                                ) ?>"
                                class="industry-page-link"
                            >
                                1
                            </a>

                            <?php if ($startPage > 2): ?>

                                <span class="industry-page-dots">
                                    ...
                                </span>

                            <?php endif; ?>

                        <?php endif; ?>

                        <?php for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ): ?>

                            <a
                                href="<?= e(
                                    industryQueryUrl([
                                        'page' => $p
                                    ])
                                ) ?>"
                                class="industry-page-link
                                    <?= $p === $page
                                        ? 'current'
                                        : ''
                                    ?>"
                            >
                                <?= $p ?>
                            </a>

                        <?php endfor; ?>

                        <?php if ($endPage < $totalPages): ?>

                            <?php if ($endPage < $totalPages - 1): ?>

                                <span class="industry-page-dots">
                                    ...
                                </span>

                            <?php endif; ?>

                            <a
                                href="<?= e(
                                    industryQueryUrl([
                                        'page' => $totalPages
                                    ])
                                ) ?>"
                                class="industry-page-link"
                            >
                                <?= $totalPages ?>
                            </a>

                        <?php endif; ?>

                        <?php if ($page < $totalPages): ?>

                            <a
                                href="<?= e(
                                    industryQueryUrl([
                                        'page' => $page + 1
                                    ])
                                ) ?>"
                                class="industry-page-link"
                                title="Next"
                            >
                                <i class="fa-solid fa-chevron-right"></i>
                            </a>

                        <?php endif; ?>

                    </div>

                </div>

            <?php endif; ?>

        <?php else: ?>

            <div class="industry-empty">

                <div class="industry-empty-icon">
                    <i class="fa-solid fa-industry"></i>
                </div>

                <h3>
                    No industries found
                </h3>

                <p>
                    <?php if (
                        $search !== '' ||
                        $statusFilter !== '' ||
                        $featuredFilter !== '' ||
                        $parentFilter > 0
                    ): ?>

                        No industry matches your current filters.
                        Try changing the filters or reset them.

                    <?php else: ?>

                        No industries have been added yet.
                        Create your first industry to get started.

                    <?php endif; ?>
                </p>

                <?php if (
                    $search !== '' ||
                    $statusFilter !== '' ||
                    $featuredFilter !== '' ||
                    $parentFilter > 0
                ): ?>

                    <a
                        href="industries.php"
                        class="industry-primary-btn"
                    >
                        <i class="fa-solid fa-rotate-left"></i>
                        Clear Filters
                    </a>

                <?php else: ?>

                    <a
                        href="add_industry.php"
                        class="industry-primary-btn"
                    >
                        <i class="fa-solid fa-plus"></i>
                        Add First Industry
                    </a>

                <?php endif; ?>

            </div>

        <?php endif; ?>

    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {

    /*
     * Auto hide alert after 5 seconds.
     */
    const alertBox =
        document.querySelector('.industry-alert');

    if (alertBox) {
        setTimeout(function () {
            alertBox.style.opacity = '0';
            alertBox.style.transform = 'translateY(-4px)';
            alertBox.style.transition = '.25s ease';

            setTimeout(function () {
                alertBox.remove();
            }, 250);

        }, 5000);
    }

});
</script>

<?php
/* ---------------------------------------------------------
   FOOTER
--------------------------------------------------------- */
$footerLoaded = false;

$footerFiles = [
    __DIR__ . '/includes/footer.php',
    __DIR__ . '/footer.php',
];

foreach ($footerFiles as $footerFile) {
    if (file_exists($footerFile)) {
        require_once $footerFile;
        $footerLoaded = true;
        break;
    }
}

if (!$footerLoaded) {
    echo '</body></html>';
}

ob_end_flush();
?>