<?php

require_once 'db.php';
require_once 'functions.php'; // ✅ ADD THIS
requireStaff();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$message = '';
$error = '';
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

$job_id = (int)($_GET['id'] ?? $_POST['job_id'] ?? 0);

if ($job_id <= 0) {
    die('Invalid job ID.');
}

function paymentTypeLabel($paymentType)
{
    $labels = [
        'fix_normal' => 'Fix normal problem',
        'meter_toner_bill' => 'Meter / Toner',
        'change_part' => 'Change Part',
        'other' => 'Other'
    ];

    return $labels[$paymentType] ?? 'Other';
}

function getUploadErrorMessage(int $errorCode): string
{
    switch ($errorCode) {
        case UPLOAD_ERR_OK:
            return 'Upload successful.';
        case UPLOAD_ERR_INI_SIZE:
            return 'File is too large for server upload limit.';
        case UPLOAD_ERR_FORM_SIZE:
            return 'File is too large for form upload limit.';
        case UPLOAD_ERR_PARTIAL:
            return 'File was only partially uploaded.';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded.';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Server temporary folder is missing.';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Server failed to write file to disk.';
        case UPLOAD_ERR_EXTENSION:
            return 'A PHP extension stopped the upload.';
        default:
            return 'Unknown upload error.';
    }
}

function iniSizeToBytes(string $value): int
{
    $value = trim($value);
    if ($value === '') {
        return 0;
    }

    $last = strtolower(substr($value, -1));
    $number = (float)$value;

    switch ($last) {
        case 'g':
            $number *= 1024;
        case 'm':
            $number *= 1024;
        case 'k':
            $number *= 1024;
            break;
    }

    return (int)$number;
}

/**
 * Human readable file size, e.g. 184 KB / 1.2 MB.
 */
function humanFileSize(int $bytes): string
{
    if ($bytes <= 0) {
        return '0 KB';
    }

    $units = ['B', 'KB', 'MB', 'GB'];
    $i = (int)floor(log($bytes, 1024));
    $i = max(0, min($i, count($units) - 1));

    $size = $bytes / (1024 ** $i);

    if ($i === 0) {
        return (int)$size . ' ' . $units[$i];
    }

    return round($size, $size < 10 ? 1 : 0) . ' ' . $units[$i];
}

/*
|--------------------------------------------------------------------------
| Load job only if assigned to current staff
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT
        j.*,
        c.customer_name AS normal_customer_name,
        m.unique_machine_no,
        m.machine_model,
        m.serial_no,
        m.customer_name AS machine_customer_name,
        m.location_text,
        m.telephone
    FROM jobs j
    INNER JOIN job_staff_assignments jsa ON j.id = jsa.job_id
    LEFT JOIN customers c ON j.customer_id = c.id
    LEFT JOIN machines m ON j.machine_id = m.id
    WHERE j.id = ? AND jsa.staff_id = ?
    LIMIT 1
");
$stmt->execute([$job_id, $_SESSION['staff_id']]);
$job = $stmt->fetch();

if (!$job) {
    die('Job not found or not assigned to you.');
}

$displayCustomerName = (($job['job_type'] ?? '') === 'machine')
    ? ($job['machine_customer_name'] ?? '')
    : ($job['normal_customer_name'] ?? '');

/*
|--------------------------------------------------------------------------
| Image conversion helpers
|--------------------------------------------------------------------------
*/
function createImageFromFile(string $sourcePath, int $imageType)
{
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            return @imagecreatefromjpeg($sourcePath);
        case IMAGETYPE_PNG:
            return @imagecreatefrompng($sourcePath);
        case IMAGETYPE_GIF:
            return @imagecreatefromgif($sourcePath);
        case IMAGETYPE_WEBP:
            if (function_exists('imagecreatefromwebp')) {
                return @imagecreatefromwebp($sourcePath);
            }
            return false;
        default:
            return false;
    }
}

function buildResizedCanvas($sourceImage, int $width, int $height, int $maxWidth, int $maxHeight)
{
    $ratio = min($maxWidth / $width, $maxHeight / $height, 1);
    $newWidth = max(1, (int)round($width * $ratio));
    $newHeight = max(1, (int)round($height * $ratio));

    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    if (!$newImage) {
        return false;
    }

    $white = imagecolorallocate($newImage, 255, 255, 255);
    imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $white);

    $copied = imagecopyresampled(
        $newImage,
        $sourceImage,
        0,
        0,
        0,
        0,
        $newWidth,
        $newHeight,
        $width,
        $height
    );

    if (!$copied) {
        imagedestroy($newImage);
        return false;
    }

    return $newImage;
}

/*
|--------------------------------------------------------------------------
| Aggressive "smallest possible" compressors.
|
| Both functions downscale the image, then keep lowering quality until the
| output is under $targetBytes (or until $minQuality is reached). Whatever
| happens, the result is always far smaller than the original upload.
|
| Tune these three knobs if you want even smaller / sharper files:
|   $maxDim      -> max width/height in pixels (lower = smaller file)
|   $targetBytes -> tries to get under this size
|   $minQuality  -> hard floor so images never become unreadable
|--------------------------------------------------------------------------
*/
function saveSmallestWebp(
    string $sourcePath,
    string $destinationPath,
    int $maxDim = 1200,
    int $targetBytes = 180000,
    int $startQuality = 72,
    int $minQuality = 35
): bool {
    if (!function_exists('getimagesize') || !function_exists('imagewebp')) {
        return false;
    }

    $imageInfo = @getimagesize($sourcePath);
    if ($imageInfo === false) {
        return false;
    }

    [$width, $height, $imageType] = $imageInfo;

    $sourceImage = createImageFromFile($sourcePath, $imageType);
    if (!$sourceImage) {
        return false;
    }

    $canvas = buildResizedCanvas($sourceImage, $width, $height, $maxDim, $maxDim);
    imagedestroy($sourceImage);

    if (!$canvas) {
        return false;
    }

    $saved = false;

    for ($quality = $startQuality; $quality >= $minQuality; $quality -= 8) {
        if (!@imagewebp($canvas, $destinationPath, $quality)) {
            $saved = false;
            break;
        }

        $saved = true;
        clearstatcache(true, $destinationPath);

        if ((int)@filesize($destinationPath) <= $targetBytes) {
            break;
        }
    }

    imagedestroy($canvas);

    return $saved;
}

function saveSmallestJpeg(
    string $sourcePath,
    string $destinationPath,
    int $maxDim = 1200,
    int $targetBytes = 180000,
    int $startQuality = 70,
    int $minQuality = 40
): bool {
    if (!function_exists('getimagesize') || !function_exists('imagejpeg')) {
        return false;
    }

    $imageInfo = @getimagesize($sourcePath);
    if ($imageInfo === false) {
        return false;
    }

    [$width, $height, $imageType] = $imageInfo;

    $sourceImage = createImageFromFile($sourcePath, $imageType);
    if (!$sourceImage) {
        return false;
    }

    $canvas = buildResizedCanvas($sourceImage, $width, $height, $maxDim, $maxDim);
    imagedestroy($sourceImage);

    if (!$canvas) {
        return false;
    }

    $saved = false;

    for ($quality = $startQuality; $quality >= $minQuality; $quality -= 8) {
        if (!@imagejpeg($canvas, $destinationPath, $quality)) {
            $saved = false;
            break;
        }

        $saved = true;
        clearstatcache(true, $destinationPath);

        if ((int)@filesize($destinationPath) <= $targetBytes) {
            break;
        }
    }

    imagedestroy($canvas);

    return $saved;
}

/*
|--------------------------------------------------------------------------
| Existing images helpers
|--------------------------------------------------------------------------
*/
function getJobImages(PDO $pdo, int $jobId): array
{
    $stmt = $pdo->prepare("
        SELECT id, image_path, image_type, created_at
        FROM job_images
        WHERE job_id = ?
        ORDER BY id DESC
    ");
    $stmt->execute([$jobId]);
    return $stmt->fetchAll() ?: [];
}

function deleteJobImages(PDO $pdo, int $jobId, array $imageIds): int
{
    $imageIds = array_values(array_filter(array_map('intval', $imageIds)));
    if (empty($imageIds)) {
        return 0;
    }

    $placeholders = implode(',', array_fill(0, count($imageIds), '?'));

    $selectStmt = $pdo->prepare("
        SELECT id, image_path
        FROM job_images
        WHERE job_id = ?
          AND id IN ($placeholders)
    ");
    $selectStmt->execute(array_merge([$jobId], $imageIds));
    $images = $selectStmt->fetchAll() ?: [];

    if (!$images) {
        return 0;
    }

    $deleteIds = [];

    foreach ($images as $img) {
        $deleteIds[] = (int)$img['id'];

        $relativePath = trim((string)$img['image_path']);
        if ($relativePath !== '') {
            $fullPath = __DIR__ . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relativePath);
            if (is_file($fullPath)) {
                @unlink($fullPath);
            }
        }
    }

    $deletePlaceholders = implode(',', array_fill(0, count($deleteIds), '?'));

    $deleteStmt = $pdo->prepare("
        DELETE FROM job_images
        WHERE job_id = ?
          AND id IN ($deletePlaceholders)
    ");
    $deleteStmt->execute(array_merge([$jobId], $deleteIds));

    return count($deleteIds);
}

/*
|--------------------------------------------------------------------------
| Save images helper
|
| $savedFiles is filled with ['name' => original name, 'bytes' => saved size]
| so the caller can show how small each image ended up.
|--------------------------------------------------------------------------
*/
function saveJobImages(
    PDO $pdo,
    int $jobId,
    array $files,
    string &$uploadError = '',
    array &$uploadWarnings = [],
    array &$savedFiles = []
): int {
    $savedCount = 0;

    if (
        !isset($files['name'], $files['tmp_name'], $files['error'], $files['size']) ||
        !is_array($files['name'])
    ) {
        return 0;
    }

    $uploadDirFs = __DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'job_images' . DIRECTORY_SEPARATOR;
    $uploadDirDb = 'uploads/job_images/';

    if (!is_dir($uploadDirFs)) {
        if (!mkdir($uploadDirFs, 0775, true) && !is_dir($uploadDirFs)) {
            $uploadError = 'Failed to create upload folder.';
            return 0;
        }
    }

    if (!is_writable($uploadDirFs)) {
        $uploadError = 'Upload folder is not writable: ' . $uploadDirFs;
        return 0;
    }

    $allowedMimeMap = [
        'image/jpeg' => true,
        'image/png'  => true,
        'image/gif'  => true,
        'image/webp' => true,
    ];

    $insertStmt = $pdo->prepare("
        INSERT INTO job_images (job_id, image_path, image_type, created_at)
        VALUES (?, ?, ?, NOW())
    ");

    foreach ($files['name'] as $index => $originalName) {
        $originalName = trim((string)($originalName ?? ''));
        $displayName = $originalName !== '' ? $originalName : ('File ' . ($index + 1));

        $fileError = (int)($files['error'][$index] ?? UPLOAD_ERR_NO_FILE);

        if ($fileError === UPLOAD_ERR_NO_FILE) {
            continue;
        }

        if ($fileError !== UPLOAD_ERR_OK) {
            $uploadWarnings[] = $displayName . ': ' . getUploadErrorMessage($fileError);
            continue;
        }

        $tmpName = (string)($files['tmp_name'][$index] ?? '');
        $fileSize = (int)($files['size'][$index] ?? 0);

        if ($tmpName === '' || !is_uploaded_file($tmpName)) {
            $uploadWarnings[] = $displayName . ' is not a valid uploaded file.';
            continue;
        }

        if ($fileSize <= 0) {
            $uploadWarnings[] = $displayName . ' is empty.';
            continue;
        }

        if ($fileSize > 50 * 1024 * 1024) {
            $uploadWarnings[] = $displayName . ' is larger than 50MB.';
            continue;
        }

        $imageInfo = @getimagesize($tmpName);
        if ($imageInfo === false) {
            $uploadWarnings[] = $displayName . ' is not a valid image.';
            continue;
        }

        $mimeType = $imageInfo['mime'] ?? '';
        if (!isset($allowedMimeMap[$mimeType])) {
            $uploadWarnings[] = $displayName . ' has unsupported format (' . $mimeType . '). iPhone HEIC photos must be converted to JPG first.';
            continue;
        }

        try {
            $randomPart = bin2hex(random_bytes(4));
        } catch (Throwable $e) {
            $randomPart = (string)mt_rand(1000, 9999);
        }

        $baseFileName = 'job_' . $jobId . '_' . date('Ymd_His') . '_' . $index . '_' . $randomPart;

        $saved = false;
        $dbPath = '';
        $imageType = 'close_job';
        $savedBytes = 0;

        // WebP first -> usually the smallest. Falls back to JPEG if the
        // server has no WebP support.
        $webpFileName = $baseFileName . '.webp';
        $webpFsPath = $uploadDirFs . $webpFileName;
        $webpDbPath = $uploadDirDb . $webpFileName;

        if (saveSmallestWebp($tmpName, $webpFsPath)) {
            $saved = true;
            $dbPath = $webpDbPath;
            clearstatcache(true, $webpFsPath);
            $savedBytes = (int)@filesize($webpFsPath);
        } else {
            $jpgFileName = $baseFileName . '.jpg';
            $jpgFsPath = $uploadDirFs . $jpgFileName;
            $jpgDbPath = $uploadDirDb . $jpgFileName;

            if (saveSmallestJpeg($tmpName, $jpgFsPath)) {
                $saved = true;
                $dbPath = $jpgDbPath;
                clearstatcache(true, $jpgFsPath);
                $savedBytes = (int)@filesize($jpgFsPath);
            }
        }

        if (!$saved) {
            $uploadWarnings[] = $displayName . ' could not be converted and saved on server.';
            continue;
        }

        $insertStmt->execute([
            $jobId,
            $dbPath,
            $imageType
        ]);

        $savedFiles[] = [
            'name'  => $displayName,
            'bytes' => $savedBytes,
        ];

        $savedCount++;
    }

    return $savedCount;
}

/*
|--------------------------------------------------------------------------
| Detect oversized POST request
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) && !empty($_SERVER['CONTENT_LENGTH'])) {
    $postMaxBytes = iniSizeToBytes((string)ini_get('post_max_size'));
    $contentLength = (int)$_SERVER['CONTENT_LENGTH'];

    if ($postMaxBytes > 0 && $contentLength > $postMaxBytes) {
        $error = 'Upload failed: total request is larger than server limit (post_max_size = ' . ini_get('post_max_size') . '). Please upload smaller image(s) or increase PHP upload limits in Plesk.';
    } else {
        $error = 'Upload failed. The request was empty or too large.';
    }
}

/*
|--------------------------------------------------------------------------
| Delete single image immediately
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_single_image'])) {
    $imageId = (int)($_POST['image_id'] ?? 0);

    if ($imageId <= 0) {
        $error = 'Invalid image selected.';
    } else {
        try {
            $deletedCount = deleteJobImages($pdo, $job_id, [$imageId]);

            if ($deletedCount > 0) {
                $_SESSION['success_message'] = 'Photo deleted successfully.';
            } else {
                $_SESSION['success_message'] = 'Photo was not found or already deleted.';
            }

            redirect('close_job.php?id=' . (int)$job_id);
        } catch (Throwable $e) {
            $error = 'Failed to delete photo. ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Submit form
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_job'])) {
    $solution_note = trim($_POST['solution_note'] ?? '');

    $hasUploadedFiles = false;

    if (isset($_FILES['job_images']['error']) && is_array($_FILES['job_images']['error'])) {
        foreach ($_FILES['job_images']['error'] as $fileError) {
            if ((int)$fileError !== UPLOAD_ERR_NO_FILE) {
                $hasUploadedFiles = true;
                break;
            }
        }
    }

    if ($solution_note === '' && !$hasUploadedFiles) {
        $error = 'Please enter solution note or upload at least one image.';
    } else {
        try {
            $pdo->beginTransaction();

            $updateStmt = $pdo->prepare("
                UPDATE jobs
                SET
                    solution_note = ?,
                    status = 'closed',
                    closed_at = COALESCE(closed_at, NOW())
                WHERE id = ?
                LIMIT 1
            ");
            $updateStmt->execute([
                $solution_note,
                $job_id
            ]);

            $uploadError = '';
            $uploadWarnings = [];
            $savedFiles = [];
            $savedImageCount = 0;

            if (isset($_FILES['job_images']) && is_array($_FILES['job_images']['name'] ?? null)) {
                $savedImageCount = saveJobImages($pdo, $job_id, $_FILES['job_images'], $uploadError, $uploadWarnings, $savedFiles);
            }

            if ($uploadError !== '') {
                throw new Exception($uploadError);
            }

            $pdo->commit();

            $wasClosedAlready = (($job['status'] ?? '') === 'closed');

            $formattedJobNo = formatJobNo($job['job_no'] ?? $job_id);
            $successMessage = 'Job ' . formatJobNo($job['job_no'] ?? $job_id) . ' '
                . ($wasClosedAlready ? 'modified successfully.' : 'closed successfully.');

            if ($savedImageCount > 0) {
                $successMessage .= ' ' . $savedImageCount . ' image(s) uploaded.';

                $sizeBits = [];
                foreach ($savedFiles as $sf) {
                    $sizeBits[] = $sf['name'] . ' → ' . humanFileSize((int)$sf['bytes']);
                }

                if (!empty($sizeBits)) {
                    $successMessage .= ' Compressed sizes: ' . implode(', ', $sizeBits) . '.';
                }
            }

            if (!empty($uploadWarnings)) {
                $successMessage .= ' Some files were skipped: ' . implode(' ', $uploadWarnings);
            }

            $_SESSION['success_message'] = $successMessage;
            redirect('staff-dashboard.php');
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = 'Failed to update job. ' . $e->getMessage();
        }
    }
}

$existingImages = getJobImages($pdo, $job_id);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Job - <?= esc(formatJobNo($job['job_no'] ?? '')) ?></title>
    <link rel="stylesheet" href="css/style.css?v=1">
    <style>
        * { box-sizing: border-box; }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }

        .container {
            max-width: 900px;
            margin: 24px auto;
            padding: 0 16px;
        }

        .box {
            background: #fff;
            border-radius: 16px;
            padding: 22px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
            margin-bottom: 20px;
        }

        .top-actions {
            margin-bottom: 16px;
        }

        .back-link {
            display: inline-block;
            text-decoration: none;
            color: #2563eb;
            font-weight: bold;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 180px 1fr;
            gap: 12px 16px;
        }

        .label {
            font-size: 13px;
            color: #6b7280;
            font-weight: bold;
        }

        .value {
            font-size: 15px;
            color: #111827;
            word-break: break-word;
        }

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

        label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: bold;
        }

        textarea,
        input[type="file"] {
            width: 100%;
            border: 1px solid #d1d5db;
            border-radius: 12px;
            padding: 12px;
            font-size: 14px;
            background: #fff;
        }

        textarea {
            min-height: 140px;
            resize: vertical;
        }

        .help {
            font-size: 12px;
            color: #6b7280;
            margin-top: 8px;
        }

        .btn-row {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn {
            display: inline-block;
            border: none;
            border-radius: 10px;
            padding: 12px 18px;
            cursor: pointer;
            font-weight: bold;
            text-decoration: none;
        }

        .btn-primary {
            background: #0284c7;
            color: #fff;
        }

        .btn-primary:hover {
            background: #0369a1;
        }

        .btn-secondary {
            background: #e5e7eb;
            color: #111827;
        }

        .btn-secondary:hover {
            background: #d1d5db;
        }

        .btn-delete {
            background: #dc2626;
            color: #fff;
            width: 100%;
            padding: 10px 12px;
            font-size: 13px;
        }

        .btn-delete:hover {
            background: #b91c1c;
        }

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .success {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 14px;
            margin-top: 12px;
        }

        .image-card {
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            padding: 10px;
            background: #fff;
        }

        .image-card a {
            text-decoration: none;
        }

        .image-card img {
            display: block;
            width: 100%;
            height: 140px;
            object-fit: cover;
            border-radius: 10px;
            background: #f3f4f6;
            margin-bottom: 8px;
        }

        .image-meta {
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 8px;
            word-break: break-word;
        }

        .image-size {
            display: inline-block;
            font-weight: bold;
            color: #0369a1;
        }

        .delete-form {
            margin: 0;
        }

        @media (max-width: 700px) {
            .info-grid {
                grid-template-columns: 1fr;
            }

            .image-grid {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="top-actions">
            <a class="back-link" href="staff-dashboard.php">← Back to Staff Dashboard</a>
        </div>

        <?php if ($error): ?>
            <div class="error"><?= esc($error) ?></div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="success"><?= esc($success_message) ?></div>
        <?php endif; ?>

        <div class="box">
            <h1><?= ($job['status'] ?? '') === 'closed' ? 'Modify Job' : 'Update Job' ?> <?= esc(formatJobNo($job['job_no'] ?? '')) ?></h1>

            <div class="info-grid">
                <div class="label">Customer</div>
                <div class="value"><?= esc($displayCustomerName ?: '-') ?></div>

                <div class="label">Machine No</div>
                <div class="value"><?= esc($job['unique_machine_no'] ?? '-') ?></div>

                <div class="label">Machine Model</div>
                <div class="value"><?= esc($job['machine_model'] ?? '-') ?></div>

                <div class="label">Serial No</div>
                <div class="value"><?= esc($job['serial_no'] ?? '-') ?></div>

                <div class="label">Location</div>
                <div class="value"><?= esc($job['location_text'] ?? '-') ?></div>

                <div class="label">Telephone</div>
                <div class="value"><?= esc($job['telephone'] ?? '-') ?></div>

                <div class="label">Payment Type</div>
                <div class="value"><?= esc(paymentTypeLabel($job['payment_type'] ?? '')) ?></div>

                <div class="label">Issue</div>
                <div class="value"><?= esc($job['issue_title'] ?? '-') ?></div>

                <div class="label">Current Status</div>
                <div class="value"><?= esc(ucwords(str_replace('_', ' ', $job['status'] ?? '-'))) ?></div>
            </div>
        </div>

        <div class="box">
            <h2><?= ($job['status'] ?? '') === 'closed' ? 'Modify Closed Job' : 'Update and Close Job' ?></h2>

            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="job_id" value="<?= (int)$job_id ?>">

                <div class="form-group">
                    <label for="solution_note">Solution Note</label>
                    <textarea id="solution_note" name="solution_note"><?= esc($job['solution_note'] ?? '') ?></textarea>
                </div>

                <?php if (!empty($existingImages)): ?>
                    <div class="form-group">
                        <label>Already Uploaded Pictures</label>

                        <div class="image-grid">
                            <?php foreach ($existingImages as $img): ?>
                                <?php
                                    $imgUrl = trim((string)($img['image_path'] ?? ''));

                                    $sizeText = '';
                                    if ($imgUrl !== '') {
                                        $fsPath = __DIR__ . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $imgUrl);
                                        if (is_file($fsPath)) {
                                            $sizeText = humanFileSize((int)filesize($fsPath));
                                        }
                                    }
                                ?>
                                <div class="image-card">
                                    <?php if ($imgUrl !== ''): ?>
                                        <a href="<?= esc($imgUrl) ?>" target="_blank">
                                            <img src="<?= esc($imgUrl) ?>" alt="Job image">
                                        </a>
                                    <?php else: ?>
                                        <div class="help">Image file missing.</div>
                                    <?php endif; ?>

                                    <div class="image-meta">
                                        <?= esc($img['created_at'] ?? '') ?>
                                        <?php if ($sizeText !== ''): ?>
                                            <br><span class="image-size"><?= esc($sizeText) ?></span>
                                        <?php endif; ?>
                                    </div>

                                    <form method="POST" class="delete-form" onsubmit="return confirm('Are you sure you want to delete this photo?');">
                                        <input type="hidden" name="job_id" value="<?= (int)$job_id ?>">
                                        <input type="hidden" name="image_id" value="<?= (int)$img['id'] ?>">
                                        <button type="submit" name="delete_single_image" class="btn btn-delete">Delete this photo</button>
                                    </form>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="help">
                            Tap the delete button on any photo to remove it immediately.
                        </div>
                    </div>
                <?php endif; ?>

                <div class="form-group">
                    <label for="job_images">Upload Pictures</label>
                    <input
                        id="job_images"
                        type="file"
                        name="job_images[]"
                        accept="image/*"
                        multiple
                    >
                    <div class="help">
                        You can upload multiple images of any size — they are automatically
                        resized and heavily compressed on the server (saved as WebP, usually
                        under 200&nbsp;KB each). Allowed: JPG, PNG, GIF, WEBP.
                        iPhone HEIC photos are not supported directly. Please convert to JPG or use Most Compatible camera format.
                    </div>
                </div>

                <div class="btn-row">
                    <button type="submit" name="close_job" class="btn btn-primary">
                        <?= ($job['status'] ?? '') === 'closed' ? 'Save Changes' : 'Update &amp; Close' ?>
                    </button>

                    <a href="staff-dashboard.php" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</body>
</html>