<?php
require_once 'db.php';
requireAdmin();

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

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

function jobImageFilePath($path)
{
    $path = trim((string)$path);

    if ($path === '') {
        return '';
    }

    $path = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $path);
    $path = preg_replace('#^(\./|\.\\\\)+#', '', $path);

    while (strpos($path, '..' . DIRECTORY_SEPARATOR) === 0) {
        $path = substr($path, 3);
    }

    return __DIR__ . DIRECTORY_SEPARATOR . $path;
}
function formatJobNo($jobNo)
{
    if (preg_match('/JOB-(\d{8})(\d{6})/', $jobNo, $matches)) {
        $dateRaw = $matches[1];
        $time    = $matches[2];

        $dateObj = DateTime::createFromFormat('Ymd', $dateRaw);
        $dateFormatted = $dateObj ? $dateObj->format('d/m/Y') : $dateRaw;

        return $dateFormatted . ' (' . $time . ')';
    }

    return $jobNo;
}

try {
    $stmt = $pdo->prepare("SELECT id, job_no, status FROM jobs WHERE id = ? LIMIT 1");
    $stmt->execute([$jobId]);
    $job = $stmt->fetch();

    if (!$job) {
        die('Job not found.');
    }

    $allowedStatuses = ['open', 'assigned', 'in_progress', 'closed'];

    if (!in_array($job['status'] ?? '', $allowedStatuses, true)) {
        die('This job cannot be deleted.');
    }

    $imgStmt = $pdo->prepare("SELECT image_path FROM job_images WHERE job_id = ?");
    $imgStmt->execute([$jobId]);
    $images = $imgStmt->fetchAll();

    $pdo->beginTransaction();

    $stmt = $pdo->prepare("DELETE FROM job_staff_assignments WHERE job_id = ?");
    $stmt->execute([$jobId]);

    $stmt = $pdo->prepare("DELETE FROM job_images WHERE job_id = ?");
    $stmt->execute([$jobId]);

    $stmt = $pdo->prepare("DELETE FROM jobs WHERE id = ? LIMIT 1");
    $stmt->execute([$jobId]);

    $pdo->commit();

    foreach ($images as $img) {
        $filePath = jobImageFilePath($img['image_path'] ?? '');
        if ($filePath !== '' && is_file($filePath)) {
            @unlink($filePath);
        }
    }

    $formattedJobNo = formatJobNo($job['job_no'] ?? '');

$_SESSION['success_message'] = 'Job ' . formatJobNo($job['job_no'] ?? $jobId) . ' deleted successfully.';
    redirect('admin-dashboard.php');
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    die('Failed to delete job. ' . $e->getMessage());
}