<?php
session_start();
include_once 'config/db.php';

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

$job_id = isset($_GET['id']) ? filter_var($_GET['id'], FILTER_VALIDATE_INT) : null;
if (!$job_id) {
    die("Invalid Job ID");
}

$stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ?");
$stmt->execute([$job_id]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$job) {
    die("Job not found");
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);

    $image_upload_dir = "uploads/images/";
    if (!is_dir($image_upload_dir)) mkdir($image_upload_dir, 0775, true);

    $allowed_image_types = ['image/jpeg', 'image/png', 'image/gif'];
    
    $image_paths = json_decode($job['images'], true) ?: [];
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $file_type = mime_content_type($tmp_name);
                if (in_array($file_type, $allowed_image_types)) {
                    $file_name = uniqid() . "_" . basename($_FILES['images']['name'][$key]);
                    $file_path = $image_upload_dir . $file_name;
                    if (move_uploaded_file($tmp_name, $file_path)) {
                        $image_paths[] = $file_path;
                    }
                }
            }
        }
    }

    if (!empty($_POST['delete_images'])) {
        $delete_images = json_decode($_POST['delete_images'], true);
       $image_paths = array_values(array_diff($image_paths, $delete_images));
    }

    $stmt = $pdo->prepare("UPDATE jobs SET title = ?, description = ?, images = ? WHERE id = ?");
    $stmt->execute([$title, $description, json_encode(array_values($image_paths)), $job_id]);
    
    header('Location: /work_list.php?success=1');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('partials/head.php'); ?>
    <style>
        .image-preview { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
        .image-preview div { position: relative; }
        .image-preview img { width: 100px; height: 100px; object-fit: cover; border-radius: 5px; }
        .delete-icon { position: absolute; top: 0; right: 0; background: red; color: white; border-radius: 50%; cursor: pointer; padding: 2px 6px; }
    </style>
</head>
<body>
    <div class="main-wrapper">
        <?php include('partials/header.php'); ?>
        <?php include('partials/sidebar.php'); ?>

        <div class="page-wrapper" style="max-height: 100vh; overflow-y: auto;">
            <div class="content">
                <div class="page-header mb-3">
                    <h4>Edit Job Information</h4>
                </div>

                <div class="row">
                    <div class="col-xl-6 d-flex">
                        <div class="card flex-fill">
                            <div class="card-header">
                                <h5 class="card-title">Job Information</h5>
                            </div>
                            <div class="card-body">
                                <form method="POST" action="" enctype="multipart/form-data">
                                    <input type="hidden" name="delete_images" id="deleteImagesInput">

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

                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea name="description" class="form-control" rows="4" required><?= htmlspecialchars($job['description']) ?></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Current Images</label>
                                        <div class="image-preview" id="imagePreview">
                                            <?php foreach (json_decode($job['images'], true) as $image): ?>
                                                <div>
                                                    <img src="<?= $image ?>" alt="Image">
                                                    <span class="delete-icon" onclick="removeImage('<?= $image ?>', this)">×</span>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Upload New Images</label>
                                        <input type="file" name="images[]" class="form-control" accept="image/*" multiple onchange="previewImages(event)">
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Upload New Video</label>
                                        <input type="file" name="video" class="form-control" accept="video/*">
                                    </div>
                                    <button type="submit" class="btn btn-success">Update Job</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let deleteImages = [];
        function removeImage(imagePath, element) {
            deleteImages.push(imagePath);
            document.getElementById("deleteImagesInput").value = JSON.stringify(deleteImages);
            element.parentElement.remove();
        }

        function previewImages(event) {
            let imagePreview = document.getElementById("imagePreview");
            imagePreview.innerHTML = "";
            for (let file of event.target.files) {
                let reader = new FileReader();
                reader.onload = function(e) {
                    let div = document.createElement("div");
                    let img = document.createElement("img");
                    img.src = e.target.result;
                    let span = document.createElement("span");
                    span.className = "delete-icon";
                    span.innerText = "×";
                    span.onclick = function() { div.remove(); };
                    div.appendChild(img);
                    div.appendChild(span);
                    imagePreview.appendChild(div);
                };
                reader.readAsDataURL(file);
            }
        }
    </script>
</body>
</html>