<?php
ob_start();
include 'includes.php';
include 'connection.php';
session_start();

if (!isset($_SESSION['admin'])) {
    header('Location: index.php');
    exit;
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 1. Bulk Delete Logic
if (isset($_POST['bulk_delete']) && isset($_POST['selected_items']) && !empty($_POST['selected_items'])) {
    $selectedIds = $_POST['selected_items'];
    foreach ($selectedIds as $id) {
        $id = (int)$id;
        // Fetch image to delete from folder
        $res = $conn->query("SELECT image FROM careers WHERE id=$id");
        if ($res->num_rows > 0) {
            $row = $res->fetch_assoc();
            if (file_exists("../" . $row['image'])) {
                unlink("../" . $row['image']);
            }
        }
        // Delete from database
        $conn->query("DELETE FROM careers WHERE id=$id");
    }
    header("Location: manage_careers.php?page=" . $page);
    exit;
}

// Single Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $res = $conn->query("SELECT image FROM careers WHERE id=$id");
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        if (file_exists("../" . $row['image'])) unlink("../" . $row['image']);
    }
    $conn->query("DELETE FROM careers WHERE id=$id");
    header("Location: manage_careers.php?page=" . ($page));
    exit;
}

// Toggle Status
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $conn->query("UPDATE careers SET status = 1-status WHERE id=$id");
    header("Location: manage_careers.php?page=" . ($page));
    exit;
}

// Slug generator
function createSlug($string)
{
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
    return strtolower(trim($slug, '-'));
}

// Add/Edit Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['bulk_delete'])) {
    $title = $conn->real_escape_string($_POST['title']);
    $slug = createSlug($title);
    $location = $conn->real_escape_string($_POST['location']);
    $salary = $conn->real_escape_string($_POST['salary']);
    $vacancy = (int)$_POST['vacancy'];
    $description = $conn->real_escape_string($_POST['description']);

    $targetDir = "../assets/careers/";
    if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

    // Edit
    if (isset($_POST['edit_id']) && !empty($_POST['edit_id'])) {
        $id = (int)$_POST['edit_id'];
        $image_sql = '';

        if (!empty($_FILES['image']['name'])) {
            $fileName = time() . "_" . basename($_FILES['image']['name']);
            $targetFile = $targetDir . $fileName;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
                $dbPath = "assets/careers/" . $fileName;
                $image_sql = ", image='$dbPath'";
                $old = $conn->query("SELECT image FROM careers WHERE id=$id")->fetch_assoc();
                if ($old && !empty($old['image']) && file_exists("../" . $old['image'])) unlink("../" . $old['image']);
            }
        }

        $sql = "UPDATE careers SET title='$title', slug='$slug', location='$location', salary='$salary', vacancy=$vacancy, description='$description' $image_sql WHERE id=$id";
        $conn->query($sql);
    } else {
        // Add
        $imagePath = "";
        if (!empty($_FILES['image']['name'])) {
            $fileName = time() . "_" . basename($_FILES['image']['name']);
            $targetFile = $targetDir . $fileName;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
                $imagePath = "assets/careers/" . $fileName;
            }
        }
        $sql = "INSERT INTO careers (title, slug, location, salary, vacancy, description, image, status) VALUES ('$title', '$slug', '$location', '$salary', $vacancy, '$description', '$imagePath', 1)";
        $conn->query($sql);
    }
    header("Location: manage_careers.php");
    exit;
}

// Fetch Data
$total_query = $conn->query("SELECT COUNT(*) as total FROM careers");
$total = $total_query->fetch_assoc()['total'];
$total_pages = ceil($total / $per_page);
$result = $conn->query("SELECT * FROM careers ORDER BY id DESC LIMIT $per_page OFFSET $offset");
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Manage Careers</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <style>
        body {
            background-image: url('../assets/images/footer-bg.png');
            background-position: center;
            background-size: cover;
            font-family: sans-serif;
            margin: 0;
            padding: 0;
        }

        .spac-content {
            padding: 15px;
            min-height: 100vh;
            background-image: url('../assets/images/footer-bg.png');
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
        }

        .spac-management-container {
            max-width: 1200px;
            margin: auto;
        }

        .spac-management-title {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: white;
        }

        .spac-upload-form {
            background: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            align-items: flex-end;
            justify-content: space-between;
            /* Push items to edges */
        }

        .spac-field {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .spac-input {
            padding: 6px 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 0.85rem;
            width: 100%;
            box-sizing: border-box;
        }

        .spac-upload-btn {
            padding: 6px 12px;
            background: brown;
            color: #fff;
            border: 1px solid white;
            border-radius: 4px;
            cursor: pointer;
        }

        .spac-bulk-btn {
            padding: 6px 12px;
            background: #dc3545;
            color: #fff;
            border: 1px solid #dc3545;
            border-radius: 4px;
            cursor: pointer;
        }

        .spac-table-container {
            overflow-x: auto;
        }

        .spac-management-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
            background: white;
        }

        .spac-management-table th {
            background: brown;
            color: white;
            padding: 8px 6px;
            text-align: left;
        }

        .spac-management-table td {
            padding: 8px 6px;
            border-bottom: 1px solid #eee;
            color: brown;
        }

        /* Checkbox styling */
        .checkbox-item {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

        .spac-btn {
            width: 28px;
            height: 28px;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            text-decoration: none;
            margin-right: 5px;
            border: none;
            cursor: pointer;
        }

        .spac-toggle-btn {
            background-color: #17a2b8;
        }

        .spac-delete-btn {
            background-color: #dc3545;
        }

        .spac-edit-btn {
            background-color: #ffc107;
            color: #212529;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }

        .pagination a,
        .pagination span {
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.9);
            color: brown;
            text-decoration: none;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .pagination a:hover {
            background: brown;
            color: white;
        }

        .pagination .current {
            background: brown;
            color: white;
            font-weight: bold;
        }

        /* Modal Styles - Small & Scrollable */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            /* Prevent body scroll when modal open */
            background-color: rgba(0, 0, 0, 0.6);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            /* 5% from top */
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            max-width: 600px;
            /* Smaller width */
            height: 70vh;
            /* Fixed height */
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        }

        .modal-body {
            overflow-y: auto;
            /* Scrollbar inside modal */
            flex-grow: 1;
            padding-right: 10px;
            /* Space for scrollbar */
        }

        .close {
            float: right;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 12px;
        }

        .form-group label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }

        /* Scrollbar styling */
        .modal-body::-webkit-scrollbar {
            width: 6px;
        }

        .modal-body::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .modal-body::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 3px;
        }
    </style>
</head>

<body>
    <div class="spac-content">
        <div class="spac-management-container">
            <h1 class="spac-management-title">Manage Careers</h1>

            <!-- Top Bar with Add and Bulk Delete -->
            <form method="POST" id="bulkForm" onsubmit="return confirm('Are you sure you want to delete selected items?')">
                <input type="hidden" name="bulk_delete" value="1">
                <div class="spac-upload-form">
                    <button type="button" class="spac-upload-btn" onclick="openAddModal()"><i class="fas fa-plus"></i> Add New Job</button>

                    <button type="submit" class="spac-bulk-btn" id="bulkDeleteBtn" style="display:none;">
                        <i class="fas fa-trash-alt"></i> Delete Selected
                    </button>
                </div>

                <div class="spac-table-container">
                    <table class="spac-management-table">
                        <thead>
                            <tr>
                                <th style="width: 30px;">
                                    <input type="checkbox" id="selectAll" class="checkbox-item">
                                </th>
                                <th>S.No</th>
                                <th>Image</th>
                                <th>Title</th>
                                <th>Location</th>
                                <th>Vacancy</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $serial = $offset + 1;
                            while ($row = $result->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <input type="checkbox" name="selected_items[]" value="<?= $row['id'] ?>" class="checkbox-item item-checkbox">
                                    </td>
                                    <td><?= $serial++ ?></td>
                                    <td><img src="../<?= htmlspecialchars($row['image']) ?>" width="50" onerror="this.src='https://via.placeholder.com/50'"></td>
                                    <td><?= htmlspecialchars($row['title']) ?></td>
                                    <td><?= htmlspecialchars($row['location']) ?></td>
                                    <td><?= $row['vacancy'] ?></td>
                                    <td>
                                        <span style="padding:3px 8px; border-radius:12px; font-size:0.75rem; background:<?= $row['status'] ? '#d4edda;color:#155724' : '#fff3cd;color:#856404' ?>">
                                            <?= $row['status'] ? 'Active' : 'Inactive' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button type="button" class="spac-btn spac-edit-btn" onclick='openEditModal(<?= json_encode($row) ?>)'><i class="fas fa-edit"></i></button>
                                        <a href="?page=<?= $page ?>&toggle=<?= $row['id'] ?>" class="spac-btn spac-toggle-btn"><i class="fas fa-<?= $row['status'] ? 'ban' : 'check' ?>"></i></a>
                                        <a href="?page=<?= $page ?>&delete=<?= $row['id'] ?>" onclick="return confirm('Delete?')" class="spac-btn spac-delete-btn"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </form>

            <!-- Pagination -->
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?page=1">First</a>
                    <a href="?page=<?= $page - 1 ?>">Prev</a>
                <?php endif; ?>

                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                    <?php if ($i == $page): ?>
                        <span class="current"><?= $i ?></span>
                    <?php else: ?>
                        <a href="?page=<?= $i ?>"><?= $i ?></a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?= $page + 1 ?>">Next</a>
                    <a href="?page=<?= $total_pages ?>">Last</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #eee; padding-bottom:10px; margin-bottom:15px;">
                <h2 id="modal-title" style="margin:0; font-size:1.2rem;">Add New Job</h2>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>

            <!-- Scrollable Body -->
            <div class="modal-body">
                <form method="POST" enctype="multipart/form-data" id="careerForm">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <div class="form-group">
                        <label>Job Title *</label>
                        <input type="text" name="title" id="edit_title" class="spac-input" required>
                    </div>
                    <div style="display:flex; gap:10px;">
                        <div class="form-group" style="flex:1;">
                            <label>Location</label>
                            <input type="text" name="location" id="edit_location" class="spac-input">
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label>Salary</label>
                            <input type="text" name="salary" id="edit_salary" class="spac-input">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Vacancy</label>
                        <input type="number" name="vacancy" id="edit_vacancy" class="spac-input" value="1">
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" id="description" rows="4"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Image</label>
                        <input type="file" name="image" class="spac-input" accept="image/*">
                    </div>
                    <button type="submit" class="spac-upload-btn" style="width:100%; padding:10px;">Save Job</button>
                </form>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        let editor1;
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize CKEditor
            editor1 = CKEDITOR.replace('description', {
                height: 150
            });

            // Select All Logic
            document.getElementById('selectAll').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.item-checkbox');
                checkboxes.forEach(cb => cb.checked = this.checked);
                toggleBulkButton();
            });

            // Individual Checkbox Logic
            document.querySelectorAll('.item-checkbox').forEach(cb => {
                cb.addEventListener('change', toggleBulkButton);
            });
        });

        function toggleBulkButton() {
            const checked = document.querySelectorAll('.item-checkbox:checked').length;
            const btn = document.getElementById('bulkDeleteBtn');
            btn.style.display = checked > 0 ? 'inline-block' : 'none';
        }

        function openAddModal() {
            document.getElementById('modal-title').innerText = "Add New Job";
            document.getElementById('careerForm').reset();
            document.getElementById('edit_id').value = '';
            if (editor1) editor1.setData('');
            document.getElementById('editModal').style.display = 'block';
        }

        function openEditModal(data) {
            document.getElementById('modal-title').innerText = "Edit Job";
            document.getElementById('edit_id').value = data.id || '';
            document.getElementById('edit_title').value = data.title || '';
            document.getElementById('edit_location').value = data.location || '';
            document.getElementById('edit_salary').value = data.salary || '';
            document.getElementById('edit_vacancy').value = data.vacancy || 1;
            setTimeout(() => {
                if (editor1) editor1.setData(data.description || '');
            }, 200);
            document.getElementById('editModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        window.onclick = function(event) {
            const modal = document.getElementById('editModal');
            if (event.target == modal) closeModal();
        }
    </script>
</body>

</html>
<?php ob_end_flush(); ?>