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

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

// Get and validate user ID from URL
$user_id = isset($_GET['id']) ? filter_var($_GET['id'], FILTER_VALIDATE_INT) : null;
if (!$user_id) {
    die("Invalid User ID");
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    
    // Ensure uploads folder exists
    $image_upload_dir = "uploads/images/";
    $video_upload_dir = "uploads/videos/";

    if (!is_dir($image_upload_dir)) mkdir($image_upload_dir, 0775, true);
    if (!is_dir($video_upload_dir)) mkdir($video_upload_dir, 0775, true);

    // Allowed file types
    $allowed_image_types = ['image/jpeg', 'image/png', 'image/gif'];
    $allowed_video_types = ['video/mp4', 'video/avi', 'video/mov'];

    // Handle images upload
    $image_paths = [];
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
                die("Error uploading image: " . $_FILES['images']['error'][$key]);
            }

            $file_type = mime_content_type($tmp_name);
            if (!in_array($file_type, $allowed_image_types)) {
                die("Invalid image format: " . $file_type);
            }

            $file_name = uniqid() . "_" . basename($_FILES['images']['name'][$key]);
            $file_path = $image_upload_dir . $file_name;

            if (!move_uploaded_file($tmp_name, $file_path)) {
                die("Failed to upload image.");
            }

            $image_paths[] = $file_path;
        }
    }

    // Handle video upload
    $video_path = null;
    if (!empty($_FILES['video']['name'])) {
        if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
            die("Error uploading video: " . $_FILES['video']['error']);
        }

        $video_type = mime_content_type($_FILES['video']['tmp_name']);
        if (!in_array($video_type, $allowed_video_types)) {
            die("Invalid video format: " . $video_type);
        }

        $video_name = uniqid() . "_" . basename($_FILES['video']['name']);
        $video_path = $video_upload_dir . $video_name;

        if (!move_uploaded_file($_FILES['video']['tmp_name'], $video_path)) {
            die("Failed to upload video.");
        }
    }

    // Insert into database
    $stmt = $pdo->prepare("INSERT INTO jobs (user_id, title, description, images, video_upload) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $title, $description, json_encode($image_paths), $video_path]);

    // Redirect after successful submission
    header('Location: https://blog.onedriveme.com/customer-list.php');
    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>Create Job Information</h4>
                    <h6>Fill in the job details below</h6>
                </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="user_id" value="<?= htmlspecialchars($user_id) ?>">

                                    <div class="mb-3">
                                        <label class="form-label">Job Title</label>
                                        <input type="text" name="title" class="form-control" required>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea name="description" class="form-control" rows="4" required></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Upload Images</label>
                                        <input type="file" name="images[]" class="form-control" accept="image/*" multiple onchange="previewImages(event)">
                                        <div class="image-preview" id="imagePreview"></div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Upload Video</label>
                                        <input type="file" name="video" class="form-control" accept="video/*">
                                    </div>

                                    <button type="submit" class="btn btn-success">Submit Job</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <?php include('partials/footer.php'); ?>

    <script>
        function previewImages(event) {
            let imagePreview = document.getElementById("imagePreview");
            imagePreview.innerHTML = ""; 

            for (let file of event.target.files) {
                if (!file.type.startsWith("image/")) {
                    alert("Invalid file type!");
                    continue;
                }

                let reader = new FileReader();
                reader.onload = function(e) {
                    let div = document.createElement("div");
                    let img = document.createElement("img");
                    img.src = e.target.result;

                    let deleteIcon = document.createElement("span");
                    deleteIcon.innerHTML = "×";
                    deleteIcon.classList.add("delete-icon");
                    deleteIcon.onclick = function() { div.remove(); };

                    div.appendChild(img);
                    div.appendChild(deleteIcon);
                    imagePreview.appendChild(div);
                };
                reader.readAsDataURL(file);
            }
        }
    </script>
</body>
</html>
