<?php
include_once __DIR__ . "/../../../config/check-login.php";
include_once __DIR__ . "/../../../config/dbcon.php";

/* Fetch logged-in user ONCE */
$user = null;

if (!empty($_SESSION['user_uid'])) {
    $stmt = $conn->prepare("
        SELECT name, email, phone, profile
        FROM users
        WHERE firebase_uid = :uid
        LIMIT 1
    ");
    $stmt->execute([':uid' => $_SESSION['user_uid']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<?php
$pageTitle = "Job";
$pageHeading = "Job";
?>

<?php include __DIR__ . '/../../../components/backend/sidebar.php'; ?>
<?php include __DIR__ . '/../../../components/backend/header.php'; ?>
<?php include __DIR__ . '/../../../config/dbcon.php'; ?>

<?php
// Fetch Published Jobs
$query = "SELECT * FROM jobs WHERE deleted_at IS NULL AND is_published = '1' AND is_draft = '0' ORDER BY id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$published_jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Draft Jobs
$query = "SELECT * FROM jobs WHERE deleted_at IS NULL AND is_draft = '1' ORDER BY id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$draft_jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php
$query = "SELECT * FROM countries WHERE deleted_at IS NULL ORDER BY country_name ASC,id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$countries = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php
$query = "SELECT * FROM states WHERE deleted_at IS NULL ORDER BY state_name ASC,id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$states = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php
$query = "SELECT * FROM cities WHERE deleted_at IS NULL ORDER BY city_name ASC, id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$cities = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php
$query = "SELECT id FROM countries WHERE deleted_at IS NULL AND country_name = 'India'";
$stmt = $conn->prepare($query);
$stmt->execute();
$india_id = $stmt->fetchColumn();
?>

<?php
$query = "SELECT * FROM jobs WHERE is_published ='0' AND is_draft='1' LIMIT 1";
$stmt = $conn->prepare($query);
$stmt->execute();
$draft_job = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
$query = "SELECT * FROM categories WHERE deleted_at IS NULL";
$stmt = $conn->prepare($query);
$stmt->execute();
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<style>
    .job-tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        border-bottom: 2px solid #e0e0e0;
    }

    .job-tab {
        padding: 12px 24px;
        background: transparent;
        border: none;
        border-bottom: 3px solid transparent;
        cursor: pointer;
        font-size: 16px;
        font-weight: 500;
        color: #666;
        transition: all 0.3s ease;
    }

    .job-tab:hover {
        color: #333;
        background: #f5f5f5;
    }

    .job-tab.active {
        color: #007bff;
        border-bottom-color: #007bff;
        font-weight: 600;
    }

    .job-tab .badge {
        margin-left: 8px;
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
    }

    .job-tab.published-tab .badge {
        background: #28a745;
        color: white;
    }

    .job-tab.draft-tab .badge {
        background: #ffc107;
        color: #333;
    }

    .tab-content {
        display: none;
    }

    .tab-content.active {
        display: block;
    }
</style>

<div class="custom-toast-container" id="toastContainer"></div>
<div class="main-wrapper">
    <div class="page-header">
        <h2 class="page-title">Job List</h2>
        <a href="#" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addJobModal"
            data-id="<?= (int) $draft_job['id'] ?>" data-india-id="<?= $india_id ?>"
            data-job='<?= json_encode($draft_job, JSON_HEX_APOS | JSON_HEX_QUOT) ?>'
            onclick="openDraftFromButton(this)">
            Add Job
        </a>
    </div>

    <!-- Tab Navigation -->
    <div class="job-tabs mt-3">
        <button class="job-tab published-tab active" onclick="switchTab('published')">
            <i class="fas fa-check-circle"></i> Published Jobs
            <span class="badge"><?= count($published_jobs) ?></span>
        </button>
        <button class="job-tab draft-tab" onclick="switchTab('draft')">
            <i class="fas fa-file-alt"></i> Draft Jobs
            <span class="badge"><?= count($draft_jobs) ?></span>
        </button>
    </div>

    <!-- Published Jobs Tab Content -->
    <div id="published-tab" class="tab-content active">
        <div class="modern-table-card">
            <div class="table-responsive-wrapper">
                <table class="modern-table">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Job Name</th>
                            <th>Job Type</th>
                            <th>Salary</th>
                            <th>Number of Vacancy</th>
                            <th>Expired Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($published_jobs)): ?>
                            <?php foreach ($published_jobs as $index => $job): ?>
                                <tr>
                                    <td data-label="#"><?= $index + 1 ?></td>
                                    <td data-label="Job Name">
                                        <?= htmlspecialchars($job['job_name']) ?>
                                    </td>
                                    <?php
                                    $jobTypeLabels = [
                                        'full_time' => 'Full Time',
                                        'part_time' => 'Part Time',
                                        'intern' => 'Intern'
                                    ];
                                    ?>
                                    <td data-label="Job Type">
                                        <?= htmlspecialchars($jobTypeLabels[$job['job_type']] ?? $job['job_type']) ?>
                                    </td>
                                    <td data-label="Salary">
                                        <?= htmlspecialchars($job['job_salary']) ?>
                                    </td>
                                    <td data-label="Number of Vacancy">
                                        <?= htmlspecialchars($job['job_available_positions']) ?>
                                    </td>
                                    <td data-label="Expired Date">
                                        <?php
                                        if (!empty($job['expiry_date'])) {
                                            $date = new DateTime($job['expiry_date']);
                                            echo $date->format('d M Y');
                                        } else {
                                            echo "-";
                                        }
                                        ?>
                                    </td>
                                    <td data-label="Action">
                                        <button class="btn btn-sm btn-outline-warning"
                                            style="width: 36px; height: 36px; display:inline-flex;align-items:center;justify-content:center;"
                                            title="Move to Draft" onclick="toggleDraftStatus(<?= $job['id'] ?>)">
                                            <i class="fas fa-arrow-down"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-primary me-1"
                                            style="width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center;"
                                            title="Edit Job" onclick='EditJob(
      <?= (int) $job["id"] ?>,
        <?= json_encode($india_id) ?>,
      <?= json_encode($job["job_name"]) ?>,
      <?= json_encode($job["job_type"]) ?>,
      <?= json_encode($job["job_description"]) ?>,
      <?= json_encode($job["job_salary"]) ?>,
      <?= json_encode($job["job_available_positions"]) ?>,
      <?= json_encode($job["apply"]) ?>,
      <?= json_encode($job["is_featured"]) ?>,
      <?= json_encode($job["country_id"]) ?>,
      <?= json_encode($job["state_id"] ?? "") ?>,
      <?= json_encode($job["city_id"] ?? "") ?>,
      <?= json_encode($job["category_id"] ?? "") ?>,    
      <?= json_encode($job["expiry_date"]) ?>
    )'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger"
                                            style="width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center;"
                                            title="Delete Job" onclick="DeleteJob(<?= $job['id'] ?>)">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center">No published jobs found</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Draft Jobs Tab Content -->
    <div id="draft-tab" class="tab-content">
        <div class="modern-table-card">
            <div class="table-responsive-wrapper">
                <table class="modern-table">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Job Name</th>
                            <th>Job Type</th>
                            <th>Salary</th>
                            <th>Number of Vacancy</th>
                            <th>Expired Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($draft_jobs)): ?>
                            <?php foreach ($draft_jobs as $index => $job): ?>
                                <tr>
                                    <td data-label="#"><?= $index + 1 ?></td>
                                    <td data-label="Job Name">
                                        <?= htmlspecialchars($job['job_name']) ?>
                                    </td>
                                    <?php
                                    $jobTypeLabels = [
                                        'full_time' => 'Full Time',
                                        'part_time' => 'Part Time',
                                        'intern' => 'Intern'
                                    ];
                                    ?>
                                    <td data-label="Job Type">
                                        <?= htmlspecialchars($jobTypeLabels[$job['job_type']] ?? $job['job_type']) ?>
                                    </td>
                                    <td data-label="Salary">
                                        <?= htmlspecialchars($job['job_salary']) ?>
                                    </td>
                                    <td data-label="Number of Vacancy">
                                        <?= htmlspecialchars($job['job_available_positions']) ?>
                                    </td>
                                    <td data-label="Expired Date">
                                        <?php
                                        if (!empty($job['expiry_date'])) {
                                            $date = new DateTime($job['expiry_date']);
                                            echo $date->format('d M Y');
                                        } else {
                                            echo "-";
                                        }
                                        ?>
                                    </td>
                                    <td data-label="Action">
                                        <button class="btn btn-sm btn-outline-success"
                                            style="width: 36px; height: 36px; display:inline-flex;align-items:center;justify-content:center;"
                                            title="Publish Job" onclick="toggleDraftStatus(<?= $job['id'] ?>)">
                                            <i class="fas fa-upload"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-primary me-1"
                                            style="width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center;"
                                            title="Edit Job" onclick='EditJob(
      <?= (int) $job["id"] ?>,
        <?= json_encode($india_id) ?>,
      <?= json_encode($job["job_name"]) ?>,
      <?= json_encode($job["job_type"]) ?>,
      <?= json_encode($job["job_description"]) ?>,
      <?= json_encode($job["job_salary"]) ?>,
      <?= json_encode($job["job_available_positions"]) ?>,
      <?= json_encode($job["apply"]) ?>,
      <?= json_encode($job["is_featured"]) ?>,
      <?= json_encode($job["country_id"]) ?>,
      <?= json_encode($job["state_id"] ?? "") ?>,
      <?= json_encode($job["city_id"] ?? "") ?>,
      <?= json_encode($job["category_id"] ?? "") ?>,
      <?= json_encode($job["expiry_date"]) ?>
    )'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger"
                                            style="width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center;"
                                            title="Delete Job" onclick="DeleteJob(<?= $job['id'] ?>)">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center">No draft jobs found</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        function switchTab(tabName) {
            // Remove active class from all tabs and contents
            document.querySelectorAll('.job-tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

            // Add active class to selected tab and content
            if (tabName === 'published') {
                document.querySelector('.published-tab').classList.add('active');
                document.getElementById('published-tab').classList.add('active');
            } else {
                document.querySelector('.draft-tab').classList.add('active');
                document.getElementById('draft-tab').classList.add('active');
            }
        }
    </script>

    <!-- ================= ADD Job MODAL ================= -->
    <div class="modal fade" id="addJobModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Job</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addJobForm" novalidate>
                        <input type="hidden" name="job_id" id="job_id" class="form-control">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Job Name</label>
                                <input type="text" name="job_name" id="job_name" class="form-control">
                                <div class="invalid-feedback" id="job-name-error"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Job Type</label>
                                <select name="job_type" id="jobType" class="form-select">
                                    <option value="">Select Job Type</option>
                                    <option value="full_time">Full Time</option>
                                    <option value="part_time">Part Time</option>
                                    <option value="intern">Intern</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Job Salary</label>
                                <input type="text" name="job_salary" id="jobSalary" class="form-control">
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Available Positions</label>
                                <input type="number" name="available_positions" id="jobPosition" class="form-control"
                                    min="1">
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Category</label>
                                <select name="category_id" id="add_category_id" class="form-select">
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?= $category['id'] ?>">
                                            <?= htmlspecialchars($category['category_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Country</label>
                                <select name="country_id" id="add_country_id" class="form-select">
                                    <option value="">Select Country</option>
                                    <?php foreach ($countries as $country): ?>
                                        <option value="<?= $country['id'] ?>">
                                            <?= htmlspecialchars($country['country_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <input type="hidden" name="india_id" id="india_id" value="<?= $india_id ?>"
                                class="form-control">
                            <div class="col-md-6 mb-3" style="display:none;" id="addState">
                                <label class="form-label">State</label>
                                <select name="state_id" id="add_state_id" class="form-select">
                                    <option value="">Select State</option>
                                    <?php foreach ($states as $state): ?>
                                        <option value="<?= $state['id'] ?>">
                                            <?= htmlspecialchars($state['state_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3" style="display:none;" id="addCity">
                                <label class="form-label">City</label>
                                <select name="city_id" id="add_city_id" class="form-select">
                                    <option value="">Select City</option>
                                    <?php foreach ($cities as $city): ?>
                                        <option value="<?= $city['id'] ?>">
                                            <?= htmlspecialchars($city['city_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Expiry Date</label>
                                <input type="date" name="expiry_date" id="expiredId" class="form-control">
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Job Description</label>
                                <textarea name="job_description" id="jobDescription" class="form-control summernote"
                                    rows="3"></textarea>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">How to Apply</label>
                                <textarea name="how_to_apply" id="howToApply" class="form-control summernote"
                                    rows="3"></textarea>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-12 form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" name="is_featured" id="is_featured"
                                    value="1">
                                <label class="form-check-label">Featured Job</label>
                            </div>
                        </div>
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-warning w-100" id="saveDraftBtn">
                                <?= !empty($draft_job['id']) ? 'Update Draft' : 'Save as Draft' ?>
                            </button>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary flex-fill">Add Job</button>
                                <button type="button" class="btn btn-secondary flex-fill"
                                    data-bs-dismiss="modal">Cancel</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= EDIT JOB MODAL ================= -->
    <div class="modal fade" id="editJobModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Job</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editJobForm" novalidate>
                        <input type="hidden" name="id" id="edit_job_id">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Job Name</label>
                                <input type="text" name="job_name" id="edit_job_name" class="form-control">
                                <div class="invalid-feedback" id="edit-job-name-error"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Job Type</label>
                                <select name="job_type" id="edit_job_type" class="form-select">
                                    <option value="">Select Job Type</option>
                                    <option value="full_time">Full Time</option>
                                    <option value="part_time">Part Time</option>
                                    <option value="intern">Intern</option>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Job Salary</label>
                                <input type="text" name="job_salary" id="edit_job_salary" class="form-control">
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Available Positions</label>
                                <input type="number" name="available_positions" id="edit_available_positions"
                                    class="form-control" min="1">
                                <div class="invalid-feedback"></div>
                            </div>
                            <input type="hidden" name="india_id1" id="india_id1" value="<?= $india_id ?>"
                                class="form-control">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Category</label>
                                <select name="category_id" id="edit_category_id" class="form-select">
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?= $category['id'] ?>">
                                            <?= htmlspecialchars($category['category_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Country</label>
                                <select name="country_id" id="edit_country_id" class="form-select">
                                    <option value="">Select Country</option>
                                    <?php foreach ($countries as $country): ?>
                                        <option value="<?= $country['id'] ?>">
                                            <?= htmlspecialchars($country['country_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3" id="edit_state">
                                <label class="form-label">State</label>
                                <select name="state_id" id="edit_state_id" class="form-select">
                                    <option value="">Select State</option>
                                    <?php foreach ($states as $state): ?>
                                        <option value="<?= $state['id'] ?>">
                                            <?= htmlspecialchars($state['state_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3" id="edit_city">
                                <label class="form-label">City</label>
                                <select name="city_id" id="edit_city_id" class="form-select">
                                    <option value="">Select City</option>
                                    <?php foreach ($cities as $city): ?>
                                        <option value="<?= $city['id'] ?>">
                                            <?= htmlspecialchars($city['city_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Expiry Date</label>
                                <input type="date" name="expiry_date" id="edit_expiry_date" class="form-control">
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Job Description</label>
                                <textarea name="job_description" id="edit_job_description"
                                    class="form-control summernote" rows="3"></textarea>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">How to Apply</label>
                                <textarea name="how_to_apply" id="edit_how_to_apply" class="form-control summernote"
                                    rows="3"></textarea>
                                <div class="invalid-feedback"></div>
                            </div>
                            <div class="col-12 form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" name="is_featured" id="edit_is_featured"
                                    value="1">
                                <label class="form-check-label">Featured Job</label>
                            </div>
                        </div>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary w-50">Update Job</button>
                            <button type="button" class="btn btn-secondary w-50" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include __DIR__ . '/../../../components/backend/footer.php'; ?>
</div>