<?php
include '../includes/db.php';

// Handle Delete
if(isset($_GET['delete_id'])){
    $id = (int)$_GET['delete_id'];
    $conn->query("DELETE FROM jobs WHERE id=$id");
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// Handle Insert / Update
$edit_id = 0;
$title = $department = $description = $requirements = $location = $deadline = $status = '';

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $title = $_POST['title'];
    $department = $_POST['department'];
    $description = $_POST['description'];
    $requirements = $_POST['requirements'];
    $location = $_POST['location'];
    $deadline = $_POST['deadline'];
    $status = $_POST['status'];
    $edit_id = isset($_POST['edit_id']) ? (int)$_POST['edit_id'] : 0;

    if($edit_id){
        $stmt = $conn->prepare("UPDATE jobs SET title=?, department=?, description=?, requirements=?, location=?, deadline=?, status=? WHERE id=?");
        $stmt->bind_param("sssssssi", $title, $department, $description, $requirements, $location, $deadline, $status, $edit_id);
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("INSERT INTO jobs (title, department, description, requirements, location, deadline, status, created_at) VALUES (?,?,?,?,?,?,?,NOW())");
        $stmt->bind_param("sssssss", $title, $department, $description, $requirements, $location, $deadline, $status);
        $stmt->execute();
    }
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// Handle Edit
if(isset($_GET['edit_id'])){
    $edit_id = (int)$_GET['edit_id'];
    $res = $conn->query("SELECT * FROM jobs WHERE id=$edit_id");
    if($res && $res->num_rows > 0){
        $job = $res->fetch_assoc();
        $title = $job['title'];
        $department = $job['department'];
        $description = $job['description'];
        $requirements = $job['requirements'];
        $location = $job['location'];
        $deadline = $job['deadline'];
        $status = $job['status'];
    } else {
        $edit_id = 0;
    }
}

// Fetch all jobs
$jobs = $conn->query("SELECT * FROM jobs ORDER BY id DESC");
if(!$jobs){
    die("Database query failed: " . $conn->error);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include 'header.php'; ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Job Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Load Poppins from Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

<!-- TinyMCE Full Package -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
  selector: '.tinymce',
  height: 400,
  menubar: true,
  plugins: 'print preview searchreplace autolink autosave save directionality \
visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor \
toc insertdatetime advlist lists checklist wordcount export formatpainter',

  toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | \
alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor backcolor | \
removeformat | pagebreak | charmap emoticons | fullscreen preview print | insertfile image media link anchor codesample | ltr rtl',

  toolbar_mode: 'floating',
  branding: false,

  // Load Poppins inside TinyMCE iframe and make it default
  content_style: "@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap'); body { font-family: 'Poppins', sans-serif; }",

  // Make Poppins appear in the font dropdown
  font_formats: "Poppins=Poppins,sans-serif; Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; Georgia=georgia,palatino,serif; Times New Roman=times new roman,times; Verdana=verdana,geneva,sans-serif"
});
</script>
</head>
<body>
<div class="container my-5">
    <h1 class="mb-4">Job Dashboard</h1>

    <!-- Job Form -->
    <div class="card mb-5">
        <div class="card-header bg-primary text-white">
            <?= $edit_id ? 'Edit Job' : 'Add New Job' ?>
        </div>
        <div class="card-body">
            <form method="post">
                <input type="hidden" name="edit_id" value="<?= $edit_id ?>">

                <div class="mb-3">
                    <label class="form-label">Title</label>
                    <input type="text" class="form-control" name="title" value="<?= htmlspecialchars($title) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Department</label>
                    <input type="text" class="form-control" name="department" value="<?= htmlspecialchars($department) ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea class="form-control tinymce" name="description"><?= htmlspecialchars($description) ?></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label">Requirements</label>
                    <textarea class="form-control tinymce" name="requirements"><?= htmlspecialchars($requirements) ?></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label">Location</label>
                    <input type="text" class="form-control" name="location" value="<?= htmlspecialchars($location) ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label">Deadline</label>
                    <input type="date" class="form-control" name="deadline" value="<?= $deadline ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label">Status</label>
                    <select class="form-select" name="status">
                        <option value="open" <?= $status=='open'?'selected':'' ?>>Open</option>
                        <option value="closed" <?= $status=='closed'?'selected':'' ?>>Closed</option>
                    </select>
                </div>

                <button type="submit" class="btn btn-success"><?= $edit_id ? 'Update Job' : 'Add Job' ?></button>
                <?php if($edit_id): ?>
                    <a href="<?= $_SERVER['PHP_SELF'] ?>" class="btn btn-secondary ms-2">Cancel</a>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <!-- Jobs Table -->
    <h2 class="mb-3">All Jobs</h2>
    <table class="table table-bordered table-striped">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Department</th>
                <th>Location</th>
                <th>Deadline</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while($job = $jobs->fetch_assoc()): ?>
            <tr>
                <td><?= $job['id'] ?></td>
                <td><?= htmlspecialchars($job['title']) ?></td>
                <td><?= htmlspecialchars($job['department']) ?></td>
                <td><?= htmlspecialchars($job['location']) ?></td>
                <td><?= $job['deadline'] ?></td>
                <td><?= $job['status'] ?></td>
                <td>
                    <a href="<?= $_SERVER['PHP_SELF'] ?>?edit_id=<?= $job['id'] ?>" class="btn btn-sm btn-primary">Edit</a>
                    <a href="<?= $_SERVER['PHP_SELF'] ?>?delete_id=<?= $job['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
