<?php
session_start();
include 'connect.php';

if (!isset($_SESSION['employer_id'])) {
    echo "You must be logged in to post a job.";
    exit(); // Stop further execution if not logged in
}

$employer_id = $_SESSION['employer_id']; // Get employer ID from session


// Handle job posting
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['job_title'])) {
    try {
        // Sanitize input data
        $job_title = $_POST['job_title'];
        $job_description = $_POST['job_description'];
        $location = $_POST['location'];
        $salary = $_POST['salary'];
        $requirements = $_POST['requirements'];
        $salary_type = $_POST['salary_type'];
        $job_type = $_POST['job_type'];
        $skills_level = $_POST['skills_level'];

        // Prepare the SQL query to insert job data into job_postings table
        $stmt = $conn->prepare(
            "INSERT INTO job_postings (employer_id, job_title, job_description, location, salary, requirements,salary_type,job_type,skills_level    ) 
             VALUES (?, ?, ?, ?, ?, ?,?,?,?)"
        );
        $stmt->bind_param(
            "issssssss", // Define parameter types (string, string, string, string, string, string)
            $employer_id,
            $job_title,
            $job_description,
            $location,
            $salary,
            $requirements,
            $salary_type,
            $job_type,
            $skills_level
        );
        $stmt->execute();

        echo "<script>alert('Job posted successfully!'); window.location.href = 'employerdash';</script>";
        exit;

    } catch (Exception $e) {
        // Return error response if an issue occurs
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en" data-theme="light">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post a New Job</title>
    <link href="https://cdn.jsdelivr.net/npm/daisyui@4.7.2/dist/full.min.css" rel="stylesheet" type="text/css" />
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>

<body class="min-h-screen bg-base-100">
    <?php include 'navbar.php'; ?>

    <main class="container mx-auto px-4 py-8">
        <!-- Breadcrumbs -->
        <div class="text-sm breadcrumbs mb-6">
            <ul class="flex items-center space-x-2">
                <li><a href="index.php" class="flex items-center text-gray-600 hover:text-primary">
                        <i class="fas fa-home mr-2"></i> Home
                    </a></li>
                <li class="flex items-center text-primary">
                    <i class="fas fa-plus-circle mr-2"></i> Post a New Job
                </li>
            </ul>
        </div>

        <!-- Main Card -->
        <div class="card bg-base-100 shadow-xl max-w-3xl mx-auto">
            <div class="card-body">
                <h2 class="card-title text-2xl font-bold mb-6 flex items-center">
                    <i class="fas fa-briefcase text-primary mr-3"></i>
                    Post a New Job Opportunity
                </h2>

                <form method="Post" action="" class="space-y-6">
                    <!-- Job Title -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fas fa-heading text-gray-400 mr-2"></i>
                                Job Title
                            </span>
                        </label>
                        <input type="text" name="job_title" placeholder="Enter job title"
                            class="input input-bordered w-full focus:input-primary" required />
                    </div>

                    <!-- Job Description -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fas fa-align-left text-gray-400 mr-2"></i>
                                Job Description
                            </span>
                        </label>
                        <textarea name="job_description" placeholder="Enter detailed job description"
                            class="textarea textarea-bordered h-32 focus:textarea-primary" required></textarea>
                    </div>

                    <!-- Location -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fas fa-location-dot text-gray-400 mr-2"></i>
                                Location
                            </span>
                        </label>
                        <input type="text" name="location" placeholder="Enter job location"
                            class="input input-bordered w-full focus:input-primary" required />
                    </div>

                    <!-- Salary -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fas fa-dollar-sign text-gray-400 mr-2"></i>
                                Salary
                            </span>
                        </label>
                        <input type="text" name="salary" placeholder="Enter salary range or fixed amount"
                            class="input input-bordered w-full focus:input-primary" required />
                    </div>

                    <!-- salary type -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fas fa-dollar-sign text-gray-400 mr-2"></i>
                                Salary type
                            </span>
                        </label>
                        <select class="select select-bordered w-full max-w-xs" name="salary_type" >
                            <option disabled selected >Select Range</option>
                            <option>Daily</option>
                            <option>Hourly</option>
                        </select>
                    </div>
                    <!-- job type -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fa-solid fa-briefcase text-gray-400 mr-2"></i>
                                Job type
                            </span>
                        </label>
                        <select class="select select-bordered w-full max-w-xs" name="job_type" >
                            <option disabled selected>Select Type</option>
                            <option>Childcare and Petcare</option>
                            <option>Cleaning and Maintenance</option>
                            <option>Delivery and Logistics</option>
                            <option>Seasonal</option>
                        </select>
                    </div>
                    <!-- Skills level -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fa-solid fa-graduation-cap text-gray-400 mr-2"></i>
                                skills level
                            </span>
                        </label>
                        <select class="select select-bordered w-full max-w-xs"name="skills_level">
                            <option disabled selected>Select Level</option>
                            <option>Entry Level</option>
                            <option>Intermediate</option>
                            <option>Experienced</option>
                        </select>
                    </div>

                    <!-- Requirements -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium flex items-center">
                                <i class="fas fa-list-check text-gray-400 mr-2"></i>
                                Requirements
                            </span>
                        </label>
                        <textarea name="requirements" placeholder="Enter job requirements"
                            class="textarea textarea-bordered h-32 focus:textarea-primary" required></textarea>
                    </div>




                    <!-- Submit Button -->
                    <div class="form-control mt-8">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane mr-2"></i>
                            Post Job
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </main>

    <?php include 'footer.php'; ?>


    <script>
        document.addEventListener('DOMContentLoaded', function () {
            fetchJobs();

            document.getElementById('postJobForm').addEventListener('submit', function (event) {
                event.preventDefault();
                postJob();
            });
        });

        // Function to fetch jobs from the database
        function fetchJobs() {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'manage_jobs.php', true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const data = JSON.parse(xhr.responseText);
                    const jobsList = document.getElementById('jobsList');
                    jobsList.innerHTML = '';
                    data.forEach(job => {
                        const jobDiv = document.createElement('div');
                        jobDiv.className = 'job';
                        jobDiv.innerHTML = `
                            <h3>${job.job_title}</h3>
                            <p><strong>Location:</strong> ${job.location}</p>
                            <p><strong>Salary:</strong> ${job.salary}</p>
                            <p><strong>Requirements:</strong> ${job.salary_type}</p>
                            <p><strong>Requirements:</strong> ${job.job_type}</p>
                            <p><strong>Requirements:</strong> ${job.skills_level}</p>
                            <p><strong>Requirements:</strong> ${job.requirements}</p>
                            <p><strong>Posted Date:</strong> ${new Date(job.posted_date).toLocaleDateString()}</p>
                            <p>${job.job_description}</p>
                            <button onclick="applyJob(this)">Quick Apply</button>
                        `;
                        jobsList.appendChild(jobDiv);
                    });
                }
            };
            xhr.send();
        }

        // Function to post a new job
        function postJob() {
            const xhr = new XMLHttpRequest();
            const form = document.getElementById('postJobForm');
            const formData = new FormData(form);

            xhr.open('POST', 'manage_jobs.php', true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.status === 'success') {
                        alert(response.message);
                        fetchJobs();
                    } else {
                        alert(response.message);
                    }
                }
            };
            xhr.send(formData);
        }

        // Function for the "Quick Apply" button
        function applyJob(button) {
            const jobDiv = button.parentElement;
            alert(`Applying for: ${jobDiv.querySelector('h3').textContent}`);
        }
    </script>
</body>

</html>