<?php
$pageTitle = "Home | Career Nest";
include_once __DIR__ . '/../../components/frontend/header.php';
?>


<?php
include_once __DIR__ . '/../../config/dbcon.php';

/* Filters */
$categoryId = $_GET['category'] ?? '';
$keywords = $_GET['keywords'] ?? '';
$location = $_GET['location'] ?? '';
$sort = $_GET['sort'] ?? '';

$sql = "
    SELECT 
        jobs.id,
        jobs.job_name AS title,
        jobs.job_description AS description,
        jobs.job_salary AS salary,
        jobs.job_available_positions AS vaccency,
        jobs.job_type AS type,
        categories.category_name AS category,
        cities.city_name AS location
    FROM jobs
    JOIN categories ON categories.id = jobs.category_id
    JOIN cities ON cities.id = jobs.city_id
    WHERE jobs.deleted_at IS NULL
";

$params = [];

/* Category filter */
if (!empty($categoryId)) {
    $sql .= " AND jobs.category_id = :category_id";
    $params[':category_id'] = $categoryId;
}

/* Keyword filter */
if (!empty($keywords)) {
    $sql .= " AND jobs.job_name LIKE :keywords";
    $params[':keywords'] = "%$keywords%";
}

/* Location filter */
if (!empty($location)) {
    $sql .= " AND cities.city_name LIKE :location";
    $params[':location'] = "%$location%";
}

if (!empty($_GET['job_type']) && is_array($_GET['job_type'])) {

    $placeholders = [];
    foreach ($_GET['job_type'] as $index => $type) {
        $key = ":job_type_$index";
        $placeholders[] = $key;
        $params[$key] = $type;
    }

    $sql .= " AND jobs.job_type IN (" . implode(',', $placeholders) . ")";
}

/* Sorting */
if ($sort === 'latest') {
    $sql .= " ORDER BY jobs.created_at DESC";
} elseif ($sort === 'oldest') {
    $sql .= " ORDER BY jobs.created_at ASC";
} else {
    $sql .= " ORDER BY jobs.id DESC";
}

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $conn->prepare("
    SELECT id, category_name 
    FROM categories 
    WHERE deleted_at IS NULL
    ORDER BY category_name ASC
");
$stmt->execute();

$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<section class="job-listing-section py-5" style="background:#f5f7fa;">
    <div class="container">

        <!-- Header -->
        <div class="job-listing-header mt-5">
            <div class="row align-items-center">
                
                <!-- Left -->
                <div class="col-md-8 d-flex align-items-start gap-3 mb-3 mb-md-0">
                    <div>
                        <h2 class="header-title">
                            Find Your Dream Job 🚀
                        </h2>
                        <p class="header-subtitle mb-0">
                            Explore opportunities, grow your career, and achieve your goals.
                        </p>
                    </div>
                </div>

                <!-- Right - Sort -->
                <div class="col-md-4">
                    <form method="get" id="sortJob">
                        <div class="sort-container d-flex align-items-center justify-content-between">
                            <label class="fw-semibold mb-0 d-flex align-items-center gap-2">
                                <i class="fas fa-sliders-h text-primary"></i> Sort
                            </label>

                            <select
                                name="sort"
                                class="form-select border-0 bg-transparent fw-semibold"
                                onchange="document.getElementById('sortJob').submit();"
                            >
                                <option value="">Select Option</option>
                                <option value="latest" <?= ($_GET['sort'] ?? '') === 'latest' ? 'selected' : ''; ?>>
                                    📅 Latest Jobs
                                </option>
                                <option value="oldest" <?= ($_GET['sort'] ?? '') === 'oldest' ? 'selected' : ''; ?>>
                                    🕒 Oldest First
                                </option>
                            </select>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="row">

            <!-- Sidebar -->
            <div class="col-lg-3 mb-4">
                <form method="get" id="searchForm">
                    <div class="filter-sidebar">

                        <h5 class="filter-title">Search Filters</h5>

                        <input type="text" name="keywords"
                            value="<?= htmlspecialchars($_GET['keywords'] ?? '') ?>"
                            class="form-control filter-input mb-3"
                            placeholder="🔎 Keywords...">

                        <input type="text" name="location"
                            value="<?= htmlspecialchars($_GET['location'] ?? '') ?>"
                            class="form-control filter-input mb-3"
                            placeholder="📍 Location...">

                        <select name="category" class="form-select filter-select mb-3">
                            <option value="">🏢 Select Category</option>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?= $category['id']; ?>"
                                    <?= ($categoryId == $category['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($category['category_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <label class="filter-section-title">💼 Job Type</label>
                        <div class="filter-checkbox-group mb-3">

                            <?php
                            $jobTypes = [
                                'full_time' => 'Full Time',
                                'part_time' => 'Part Time',
                                'intern' => 'Intern'
                            ];

                            $selectedTypes = $_GET['job_type'] ?? [];
                            ?>

                            <?php foreach ($jobTypes as $key => $label): ?>
                                <div class="form-check">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        name="job_type[]"
                                        value="<?= $key; ?>"
                                        id="job-type-<?= $key; ?>"
                                        <?= in_array($key, $selectedTypes) ? 'checked' : ''; ?>
                                    >
                                    <label class="form-check-label" for="job-type-<?= $key; ?>">
                                        <?= $label; ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <button class="btn btn-search-filter w-100">
                            <i class="fa fa-search me-2"></i> Apply Filters
                        </button>
                    </div>
                </form>
            </div>

            <!-- Jobs Grid -->
            <div class="col-lg-9">
                <div class="row g-4">

                    <?php if (!empty($jobs)): ?>
                        <?php foreach ($jobs as $job): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="job-card position-relative">

                                    <div class="job-card-header">
                                        <span class="category-badge">
                                            <i class="bi bi-briefcase-fill"></i>
                                            <?= htmlspecialchars($job['category']); ?>
                                        </span>
                                    </div>

                                    <div class="job-card-body">
                                        <h5 class="job-title">
                                            <?= htmlspecialchars($job['title']); ?>
                                        </h5>
                                        
                                        <p class="job-description">
                                            <?php
                                                $words = explode(' ', strip_tags($job['description']));
                                                $truncated = implode(' ', array_slice($words, 0, 30));
                                                if (count($words) > 30) {
                                                    $truncated .= '...';
                                                }
                                                echo $truncated;
                                            ?>
                                        </p>

                                        <ul class="job-meta-list">
                                            <li class="job-meta-item">
                                                <i class="fa fa-map-marker-alt icon-location"></i>
                                                <span><?= htmlspecialchars($job['location']); ?></span>
                                            </li>
                                            <li class="job-meta-item">
                                                <i class="fa fa-clock icon-clock"></i>
                                                <span><?= ucfirst(str_replace('_', ' ', htmlspecialchars($job['type']))); ?></span>
                                            </li>
                                            <li class="job-meta-item">
                                                <i class="fa fa-briefcase icon-briefcase"></i>
                                                <span>Vacancy: <?= htmlspecialchars($job['vaccency']); ?></span>
                                            </li>
                                            <li class="job-meta-item">
                                                <i class="fa fa-rupee icon-salary"></i>
                                                <span><?= htmlspecialchars($job['salary']); ?></span>
                                            </li>
                                        </ul>

                                        <a href="<?= $baseURL ?>/view/frontend/job-details.php?id=<?= $job['id']; ?>"
                                            class="btn-view-job w-100">
                                            <i class="fa fa-eye"></i> View Details
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-12">
                            <div class="no-jobs-alert">
                                <i class="fas fa-search fa-3x"></i>
                                <p>No jobs found matching your criteria. Try adjusting your filters!</p>
                            </div>
                        </div>
                    <?php endif; ?>

                </div>
            </div>
        </div>
    </div>
</section>

<?php
include_once __DIR__ . '/../../components/frontend/footer.php';
?>