<?php
echo message_box('success');
echo message_box('error');

$all_job_circular = $this->db->where('status', 'published')->order_by('posted_date', 'DESC')->get('tbl_job_circular')->result();
$openJobs = !empty($all_job_circular) ? count($all_job_circular) : 0;
$activeJobs = 0;
$closingSoon = 0;
$expiredJobs = 0;
$departments = array();

$formatText = function ($value, $fallback = '-') {
    $value = trim(strip_tags((string) $value));
    return $value !== '' ? $value : $fallback;
};

$excerpt = function ($description, $limit = 180) {
    $text = trim(preg_replace('/\s+/', ' ', strip_tags((string) $description)));
    if ($text === '') {
        return '';
    }
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return mb_strlen($text) > $limit ? mb_substr($text, 0, $limit) . '...' : $text;
    }
    return strlen($text) > $limit ? substr($text, 0, $limit) . '...' : $text;
};

$getDesignation = function ($designationId) {
    if (empty($designationId)) {
        return '-';
    }
    $designInfo = $this->db->where('designations_id', $designationId)->get('tbl_designations')->row();
    return !empty($designInfo->designations) ? $designInfo->designations : '-';
};

$getJobState = function ($lastDate) {
    $today = new DateTime(date('Y-m-d'));
    $deadline = new DateTime(date('Y-m-d', strtotime($lastDate)));
    if ($today > $deadline) {
        return array('class' => 'is-expired', 'label' => lang('expired'), 'days' => 0, 'open' => false);
    }
    $days = (int) $today->diff($deadline)->format('%a');
    if ($days === 0) {
        return array('class' => 'is-today', 'label' => lang('last_date'), 'days' => 0, 'open' => true);
    }
    return array('class' => $days <= 7 ? 'is-soon' : 'is-open', 'label' => $days . ' ' . lang('days'), 'days' => $days, 'open' => true);
};

if (!empty($all_job_circular)) {
    foreach ($all_job_circular as $job) {
        $state = $getJobState($job->last_date);
        if (!empty($state['open'])) {
            $activeJobs++;
        } else {
            $expiredJobs++;
        }
        if (!empty($state['open']) && (int) $state['days'] <= 7) {
            $closingSoon++;
        }
        $designation = $getDesignation($job->designations_id);
        if ($designation !== '-') {
            $departments[$designation] = true;
        }
    }

    usort($all_job_circular, function ($a, $b) use ($getJobState) {
        $stateA = $getJobState($a->last_date);
        $stateB = $getJobState($b->last_date);
        if (!empty($stateA['open']) !== !empty($stateB['open'])) {
            return !empty($stateA['open']) ? -1 : 1;
        }
        return strtotime($b->posted_date) <=> strtotime($a->posted_date);
    });
}
?>

<style>
    .careers-page {
        --career-ink: #0f172a;
        --career-muted: #64748b;
        --career-line: #dbe3ee;
        --career-soft: #f6f8fb;
        --career-surface: #ffffff;
        --career-elevated: #f8fafc;
        --career-card: #ffffff;
        --career-primary: #1d4ed8;
        --career-primary-dark: #173f9f;
        --career-success: #047857;
        --career-warning: #b45309;
        --career-danger: #b91c1c;
        --career-shadow: 0 12px 28px rgba(15, 23, 42, .05);
        margin: -20px -15px 0;
        background: var(--career-soft);
        color: var(--career-ink);
        font-family: Inter, "Source Sans Pro", Arial, sans-serif;
    }

    body.frontend-dark .careers-page {
        --career-ink: #e5edf8;
        --career-muted: #94a3b8;
        --career-line: #263244;
        --career-soft: #0b1120;
        --career-surface: #111827;
        --career-elevated: #0f172a;
        --career-card: #111827;
        --career-primary: #60a5fa;
        --career-primary-dark: #3b82f6;
        --career-success: #34d399;
        --career-warning: #fbbf24;
        --career-danger: #f87171;
        --career-shadow: 0 18px 34px rgba(0, 0, 0, .22);
    }

    .careers-shell {
        width: min(1180px, calc(100% - 32px));
        margin: 0 auto;
    }

    .careers-hero {
        border-bottom: 1px solid var(--career-line);
        background: var(--career-surface);
    }

    .careers-hero-inner {
        display: grid;
        grid-template-columns: minmax(0, 1.35fr) minmax(280px, 0.65fr);
        gap: 40px;
        align-items: end;
        padding: 58px 0 34px;
    }

    .careers-eyebrow {
        display: inline-flex;
        align-items: center;
        width: fit-content;
        border: 1px solid var(--career-line);
        border-radius: 999px;
        background: var(--career-elevated);
        padding: 7px 11px;
        color: var(--career-muted);
        font-size: 11px;
        font-weight: 800;
        letter-spacing: .12em;
        text-transform: uppercase;
    }

    .careers-title {
        max-width: 760px;
        margin: 18px 0 0;
        color: var(--career-ink);
        font-size: clamp(34px, 6vw, 64px);
        font-weight: 800;
        letter-spacing: 0;
        line-height: 1.02;
    }

    .careers-copy {
        max-width: 650px;
        margin: 18px 0 0;
        color: var(--career-muted);
        font-size: 16px;
        line-height: 1.75;
    }

    .careers-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin-top: 28px;
    }

    .careers-button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-height: 42px;
        border-radius: 8px;
        border: 1px solid transparent;
        padding: 0 16px;
        font-size: 14px;
        font-weight: 800;
        text-decoration: none;
        transition: background .15s ease, border-color .15s ease, color .15s ease;
    }

    .careers-button-primary {
        background: var(--career-primary);
        color: #ffffff;
    }

    .careers-button-primary:hover {
        background: var(--career-primary-dark);
        color: #ffffff;
        text-decoration: none;
    }

    .careers-button-secondary {
        border-color: var(--career-line);
        background: var(--career-surface);
        color: var(--career-ink);
    }

    .careers-button-secondary:hover {
        border-color: #b8c4d6;
        color: var(--career-ink);
        text-decoration: none;
    }

    .careers-hero-panel {
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-elevated);
        padding: 18px;
    }

    .careers-hero-panel-title {
        margin: 0 0 12px;
        color: var(--career-muted);
        font-size: 12px;
        font-weight: 800;
        letter-spacing: .1em;
        text-transform: uppercase;
    }

    .careers-stats {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 10px;
    }

    .careers-stat {
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-surface);
        padding: 14px;
    }

    .careers-stat strong {
        display: block;
        color: var(--career-ink);
        font-size: 26px;
        line-height: 1;
    }

    .careers-stat span {
        display: block;
        margin-top: 7px;
        color: var(--career-muted);
        font-size: 12px;
        font-weight: 700;
    }

    .careers-main {
        padding: 34px 0 52px;
    }

    .careers-section-head {
        display: flex;
        align-items: end;
        justify-content: space-between;
        gap: 20px;
        margin-bottom: 18px;
    }

    .careers-section-head h2 {
        margin: 0;
        color: var(--career-ink);
        font-size: 22px;
        font-weight: 800;
    }

    .careers-section-head p {
        margin: 6px 0 0;
        color: var(--career-muted);
        font-size: 14px;
    }

    .careers-count {
        white-space: nowrap;
        border: 1px solid var(--career-line);
        border-radius: 999px;
        background: var(--career-surface);
        padding: 7px 11px;
        color: var(--career-muted);
        font-size: 12px;
        font-weight: 800;
    }

    .careers-grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 16px;
    }

    .career-card {
        display: flex;
        min-height: 100%;
        flex-direction: column;
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-card);
        box-shadow: var(--career-shadow);
        overflow: hidden;
    }

    .career-card[hidden] {
        display: none;
    }

    .career-card.is-expired-card {
        border-style: dashed;
        opacity: .78;
    }

    .career-card.is-expired-card .career-link {
        background: transparent;
        border: 1px solid var(--career-line);
        color: var(--career-muted);
    }

    .career-card.is-expired-card .career-link:hover {
        border-color: var(--career-danger);
        color: var(--career-danger);
        background: transparent;
    }

    .career-card-body {
        display: flex;
        flex: 1;
        flex-direction: column;
        padding: 22px;
    }

    .career-card-top {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 14px;
    }

    .career-status {
        display: inline-flex;
        align-items: center;
        border-radius: 999px;
        padding: 6px 9px;
        font-size: 11px;
        font-weight: 800;
        line-height: 1;
        white-space: nowrap;
    }

    .career-status.is-open {
        background: rgba(16, 185, 129, .12);
        color: var(--career-success);
    }

    .career-status.is-soon,
    .career-status.is-today {
        background: rgba(245, 158, 11, .14);
        color: var(--career-warning);
    }

    .career-status.is-expired {
        background: rgba(239, 68, 68, .12);
        color: var(--career-danger);
    }

    .career-card h3 {
        margin: 0;
        color: var(--career-ink);
        font-size: 20px;
        font-weight: 800;
        line-height: 1.25;
    }

    .career-card h3 a {
        color: inherit;
        text-decoration: none;
    }

    .career-card h3 a:hover {
        color: var(--career-primary);
    }

    .career-designation {
        margin-top: 8px;
        color: var(--career-muted);
        font-size: 13px;
        font-weight: 700;
    }

    .career-meta {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 10px;
        margin: 18px 0;
    }

    .career-meta-item {
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-elevated);
        padding: 10px;
    }

    .career-meta-item span {
        display: block;
        color: var(--career-muted);
        font-size: 11px;
        font-weight: 800;
        text-transform: uppercase;
    }

    .career-meta-item strong {
        display: block;
        margin-top: 5px;
        color: var(--career-ink);
        font-size: 13px;
        font-weight: 800;
    }

    .career-description {
        flex: 1;
        margin: 0 0 20px;
        color: var(--career-muted);
        font-size: 14px;
        line-height: 1.7;
    }

    .career-card-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
        border-top: 1px solid var(--career-line);
        padding-top: 16px;
    }

    .career-deadline {
        color: var(--career-muted);
        font-size: 12px;
        font-weight: 700;
    }

    .career-link {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-height: 36px;
        border-radius: 8px;
        background: var(--career-ink);
        padding: 0 13px;
        color: #ffffff;
        font-size: 13px;
        font-weight: 800;
        text-decoration: none;
        white-space: nowrap;
    }

    .career-link:hover {
        background: var(--career-primary);
        color: #ffffff;
        text-decoration: none;
    }

    .careers-empty {
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-surface);
        padding: 42px 24px;
        text-align: center;
        color: var(--career-muted);
        box-shadow: var(--career-shadow);
    }

    .careers-empty strong {
        display: block;
        margin-bottom: 8px;
        color: var(--career-ink);
        font-size: 20px;
    }

    .careers-controls {
        display: none;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
        margin-top: 22px;
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-surface);
        padding: 12px;
    }

    .careers-controls.is-visible {
        display: flex;
    }

    .careers-pagination {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
    }

    .careers-page-btn,
    .careers-load-more {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-height: 34px;
        border: 1px solid var(--career-line);
        border-radius: 8px;
        background: var(--career-elevated);
        color: var(--career-ink);
        padding: 0 11px;
        font-size: 12px;
        font-weight: 800;
        transition: background .15s ease, border-color .15s ease, color .15s ease;
    }

    .careers-page-btn:hover,
    .careers-load-more:hover,
    .careers-page-btn.is-active {
        border-color: var(--career-primary);
        background: var(--career-primary);
        color: #ffffff;
    }

    .careers-load-more[disabled] {
        cursor: not-allowed;
        opacity: .55;
    }

    .careers-showing {
        color: var(--career-muted);
        font-size: 12px;
        font-weight: 800;
        white-space: nowrap;
    }

    @media (max-width: 900px) {
        .careers-hero-inner,
        .careers-grid {
            grid-template-columns: 1fr;
        }

        .careers-hero-inner {
            padding-top: 38px;
        }
    }

    @media (max-width: 640px) {
        .careers-page {
            margin-left: -10px;
            margin-right: -10px;
        }

        .careers-section-head,
        .career-card-top,
        .career-card-footer,
        .careers-controls {
            align-items: flex-start;
            flex-direction: column;
        }

        .career-meta,
        .careers-stats {
            grid-template-columns: 1fr;
        }

        .career-link,
        .careers-button,
        .careers-load-more {
            width: 100%;
        }
    }
</style>

<div class="careers-page">
    <section class="careers-hero">
        <div class="careers-shell careers-hero-inner">
            <div>
                <span class="careers-eyebrow"><?= lang('job_circular') ?></span>
                <h1 class="careers-title"><?= lang('all_job_circular') ?></h1>
                <p class="careers-copy">
                    Explore current openings, review the role details, and apply to the opportunity that best matches your experience.
                </p>
                <div class="careers-actions">
                    <a href="#open-roles" class="careers-button careers-button-primary"><?= lang('view') ?> <?= lang('all') ?></a>
                    <a href="<?= base_url('knowledgebase') ?>" class="careers-button careers-button-secondary"><?= lang('knowledgebase') ?></a>
                </div>
            </div>

            <aside class="careers-hero-panel" aria-label="<?= html_escape(lang('job_summery')) ?>">
                <p class="careers-hero-panel-title"><?= lang('job_summery') ?></p>
                <div class="careers-stats">
                    <div class="careers-stat">
                        <strong><?= (int) $openJobs ?></strong>
                        <span><?= lang('all_job_circular') ?></span>
                    </div>
                    <div class="careers-stat">
                        <strong><?= (int) $activeJobs ?></strong>
                        <span>Open now</span>
                    </div>
                    <div class="careers-stat">
                        <strong><?= (int) $closingSoon ?></strong>
                        <span>Closing soon</span>
                    </div>
                    <div class="careers-stat">
                        <strong><?= (int) $expiredJobs ?></strong>
                        <span>Archived</span>
                    </div>
                </div>
            </aside>
        </div>
    </section>

    <main class="careers-shell careers-main" id="open-roles">
        <div class="careers-section-head">
            <div>
                <h2>Open roles</h2>
                <p>Clear role details, deadlines, and application access in one place.</p>
            </div>
            <span class="careers-count"><?= (int) $openJobs ?> openings</span>
        </div>

        <?php if (!empty($all_job_circular)) { ?>
            <div class="careers-grid" data-careers-grid>
                <?php foreach ($all_job_circular as $index => $v_job_circular) {
                    $state = $getJobState($v_job_circular->last_date);
                    $designation = $getDesignation($v_job_circular->designations_id);
                    $detailsUrl = base_url('frontend/circular_details/' . (int) $v_job_circular->job_circular_id);
                    $isExpired = empty($state['open']);
                    ?>
                    <article class="career-card <?= $isExpired ? 'is-expired-card' : '' ?>" data-career-card data-career-index="<?= (int) $index ?>" <?= $index > 5 ? 'hidden' : '' ?>>
                        <div class="career-card-body">
                            <div class="career-card-top">
                                <div>
                                    <h3>
                                        <a href="<?= $detailsUrl ?>"><?= html_escape($formatText($v_job_circular->job_title)) ?></a>
                                    </h3>
                                    <div class="career-designation"><?= html_escape($designation) ?></div>
                                </div>
                                <span class="career-status <?= html_escape($state['class']) ?>"><?= html_escape($state['label']) ?></span>
                            </div>

                            <div class="career-meta">
                                <div class="career-meta-item">
                                    <span><?= lang('experience') ?></span>
                                    <strong><?= html_escape($formatText($v_job_circular->experience)) ?></strong>
                                </div>
                                <div class="career-meta-item">
                                    <span><?= lang('employment_type') ?></span>
                                    <strong><?= html_escape(lang($v_job_circular->employment_type)) ?></strong>
                                </div>
                                <div class="career-meta-item">
                                    <span><?= lang('vacancy_no') ?></span>
                                    <strong><?= html_escape($formatText($v_job_circular->vacancy_no)) ?></strong>
                                </div>
                                <div class="career-meta-item">
                                    <span><?= lang('posted_date') ?></span>
                                    <strong><?= display_date($v_job_circular->posted_date) ?></strong>
                                </div>
                            </div>

                            <p class="career-description"><?= html_escape($excerpt($v_job_circular->description)) ?></p>

                            <div class="career-card-footer">
                                <span class="career-deadline">
                                    <?= $isExpired ? 'Applications closed' : lang('last_date') . ': ' . display_date($v_job_circular->last_date) ?>
                                </span>
                                <a href="<?= $detailsUrl ?>" class="career-link"><?= $isExpired ? 'View archive' : 'View details' ?></a>
                            </div>
                        </div>
                    </article>
                <?php } ?>
            </div>
            <div class="careers-controls <?= count($all_job_circular) > 6 ? 'is-visible' : '' ?>" data-careers-controls>
                <div class="careers-pagination" data-careers-pagination></div>
                <span class="careers-showing" data-careers-showing></span>
                <button type="button" class="careers-load-more" data-careers-load-more>Load more</button>
            </div>
        <?php } else { ?>
            <div class="careers-empty">
                <strong><?= lang('nothing_to_display') ?></strong>
                <span>Please check back later for new opportunities.</span>
            </div>
        <?php } ?>
    </main>
</div>

<script>
    (function () {
        var cards = Array.prototype.slice.call(document.querySelectorAll('[data-career-card]'));
        var controls = document.querySelector('[data-careers-controls]');
        var pagination = document.querySelector('[data-careers-pagination]');
        var loadMore = document.querySelector('[data-careers-load-more]');
        var showing = document.querySelector('[data-careers-showing]');
        var pageSize = 6;
        var visibleCount = Math.min(pageSize, cards.length);
        var ticking = false;

        if (!cards.length || !controls) {
            return;
        }

        function totalPages() {
            return Math.max(1, Math.ceil(cards.length / pageSize));
        }

        function currentPage() {
            return Math.max(1, Math.ceil(visibleCount / pageSize));
        }

        function renderCards() {
            cards.forEach(function (card, index) {
                card.hidden = index >= visibleCount;
            });
            if (showing) {
                showing.textContent = 'Showing ' + Math.min(visibleCount, cards.length) + ' of ' + cards.length;
            }
            if (loadMore) {
                loadMore.disabled = visibleCount >= cards.length;
                loadMore.textContent = visibleCount >= cards.length ? 'All roles loaded' : 'Load more';
            }
            renderPagination();
        }

        function renderPagination() {
            if (!pagination) {
                return;
            }
            pagination.innerHTML = '';
            if (cards.length <= pageSize) {
                controls.classList.remove('is-visible');
                return;
            }
            controls.classList.add('is-visible');
            for (var page = 1; page <= totalPages(); page++) {
                var button = document.createElement('button');
                button.type = 'button';
                button.className = 'careers-page-btn' + (page === currentPage() ? ' is-active' : '');
                button.textContent = page;
                button.setAttribute('data-page', page);
                pagination.appendChild(button);
            }
        }

        function showPage(page) {
            visibleCount = Math.min(cards.length, Math.max(pageSize, page * pageSize));
            renderCards();
        }

        function showMore() {
            if (visibleCount >= cards.length) {
                return;
            }
            visibleCount = Math.min(cards.length, visibleCount + pageSize);
            renderCards();
        }

        if (pagination) {
            pagination.addEventListener('click', function (event) {
                var button = event.target.closest('[data-page]');
                if (!button) {
                    return;
                }
                showPage(parseInt(button.getAttribute('data-page'), 10) || 1);
            });
        }

        if (loadMore) {
            loadMore.addEventListener('click', showMore);
        }

        window.addEventListener('scroll', function () {
            if (ticking || visibleCount >= cards.length) {
                return;
            }
            ticking = true;
            window.requestAnimationFrame(function () {
                ticking = false;
                var nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 420;
                if (nearBottom) {
                    showMore();
                }
            });
        }, { passive: true });

        renderCards();
    })();
</script>
