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

$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 jobImageUrl($path)
{
    $path = trim((string)$path);

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

    $path = str_replace('\\', '/', $path);

    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    $path = preg_replace('#^\./#', '', $path);

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

    return $path;
}

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 formatFileSize($bytes)
{
    $bytes = (int)$bytes;

    if ($bytes <= 0) {
        return '-';
    }

    if ($bytes >= 1024 * 1024) {
        return number_format($bytes / (1024 * 1024), 2) . ' MB';
    }

    if ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    }

    return $bytes . ' B';
}

/*
|--------------------------------------------------------------------------
| Load job
|--------------------------------------------------------------------------
*/
$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
    LEFT JOIN customers c ON j.customer_id = c.id
    LEFT JOIN machines m ON j.machine_id = m.id
    WHERE j.id = ?
    LIMIT 1
");
$stmt->execute([$job_id]);
$job = $stmt->fetch();

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

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

/*
|--------------------------------------------------------------------------
| Messages + allowed statuses
|--------------------------------------------------------------------------
*/
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);
$error = '';

$allowedStatuses = [
    'open'        => 'Open',
    'assigned'    => 'Assigned',
    'in_progress' => 'In Progress',
    'closed'      => 'Closed',
];

/*
|--------------------------------------------------------------------------
| Admin: delete a staff-uploaded image
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_image'])) {
    $imageId = (int)($_POST['image_id'] ?? 0);

    if ($imageId <= 0) {
        $error = 'Invalid image selected.';
    } else {
        try {
            $sel = $pdo->prepare("
                SELECT id, image_path
                FROM job_images
                WHERE job_id = ? AND id = ?
                LIMIT 1
            ");
            $sel->execute([$job_id, $imageId]);
            $imgRow = $sel->fetch();

            if (!$imgRow) {
                $_SESSION['success_message'] = 'Image was not found or already deleted.';
            } else {
                $fsPath = jobImageFilePath($imgRow['image_path'] ?? '');
                if ($fsPath !== '' && is_file($fsPath)) {
                    @unlink($fsPath);
                }

                $del = $pdo->prepare("
                    DELETE FROM job_images
                    WHERE job_id = ? AND id = ?
                    LIMIT 1
                ");
                $del->execute([$job_id, $imageId]);

                $_SESSION['success_message'] = 'Image deleted successfully.';
            }

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

/*
|--------------------------------------------------------------------------
| Admin: change job status (e.g. reopen a closed job)
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $newStatus = (string)($_POST['new_status'] ?? '');

    if (!isset($allowedStatuses[$newStatus])) {
        $error = 'Invalid status selected.';
    } else {
        try {
            if ($newStatus === 'closed') {
                // Keep an existing closed_at, otherwise stamp now.
                $upd = $pdo->prepare("
                    UPDATE jobs
                    SET status = 'closed',
                        closed_at = COALESCE(closed_at, NOW())
                    WHERE id = ?
                    LIMIT 1
                ");
                $upd->execute([$job_id]);
            } else {
                // Reopening (or any non-closed status) clears closed_at.
                $upd = $pdo->prepare("
                    UPDATE jobs
                    SET status = ?,
                        closed_at = NULL
                    WHERE id = ?
                    LIMIT 1
                ");
                $upd->execute([$newStatus, $job_id]);
            }

            $_SESSION['success_message'] = 'Job status updated to "' . $allowedStatuses[$newStatus] . '".';
            redirect('view_job.php?id=' . $job_id);
        } catch (Throwable $e) {
            $error = 'Failed to update status. ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Load images
|--------------------------------------------------------------------------
*/
$images = [];

try {
    $imgStmt = $pdo->prepare("
        SELECT *
        FROM job_images
        WHERE job_id = ?
        ORDER BY id ASC
    ");
    $imgStmt->execute([$job_id]);
    $images = $imgStmt->fetchAll();
} catch (Exception $e) {
    $images = [];
}

$statusClass = 'status-' . ($job['status'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Job - <?= esc($job['job_no']) ?></title>

    <style>
        * { box-sizing: border-box; }

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

        .topbar {
            background: #ffffff;
            border-bottom: 1px solid #e5e7eb;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .topbar-inner {
            max-width: 1000px;
            margin: 0 auto;
            padding: 14px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
            color: #1d4ed8;
            font-weight: bold;
            font-size: 14px;
        }

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

        .top-title {
            font-size: 15px;
            font-weight: bold;
            color: #111827;
        }

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

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

        .job-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 18px;
            flex-wrap: wrap;
        }

        h1, h2 {
            margin-top: 0;
        }

        .job-header h1 {
            margin: 0;
            font-size: 28px;
        }

        .status {
            display: inline-block;
            padding: 7px 12px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-open {
            background: #dbeafe;
            color: #1d4ed8;
        }

        .status-assigned {
            background: #fef3c7;
            color: #92400e;
        }

        .status-in_progress {
            background: #e0e7ff;
            color: #4338ca;
        }

        .status-closed {
            background: #dcfce7;
            color: #166534;
        }

        .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;
        }

        /* Status control */
        .status-control {
            margin-top: 20px;
            padding-top: 18px;
            border-top: 1px solid #e5e7eb;
        }

        .status-control label {
            display: block;
            font-size: 13px;
            font-weight: bold;
            color: #6b7280;
            margin-bottom: 8px;
        }

        .status-row {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        .status-row select {
            border: 1px solid #d1d5db;
            border-radius: 10px;
            padding: 10px 12px;
            font-size: 14px;
            background: #fff;
            min-width: 180px;
        }

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

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

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

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

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

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

        .image-list {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 18px;
        }

        .image-card {
            border: 1px solid #e5e7eb;
            border-radius: 14px;
            padding: 14px;
            background: #f8fafc;
        }

        .image-card img {
            width: 100%;
            max-height: 320px;
            object-fit: cover;
            display: block;
            border-radius: 10px;
            background: #e5e7eb;
        }

        .cap {
            margin-top: 10px;
            font-size: 13px;
            color: #374151;
            line-height: 1.6;
        }

        .open-link {
            display: inline-block;
            margin-top: 10px;
            color: #2563eb;
            text-decoration: none;
            font-weight: bold;
        }

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

        .delete-form {
            margin: 12px 0 0;
        }

        .btn-delete {
            background: #dc2626;
            color: #fff;
            border: none;
            border-radius: 10px;
            padding: 9px 12px;
            font-size: 13px;
            font-weight: bold;
            cursor: pointer;
            width: 100%;
        }

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

        .empty-note {
            color: #6b7280;
            margin: 0;
        }

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

            .job-header h1 {
                font-size: 22px;
            }

            .topbar-inner {
                align-items: flex-start;
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="topbar">
        <div class="topbar-inner">
            <a class="back-link" href="admin-dashboard.php">
                ← Back to Admin Dashboard
            </a>
            <div class="top-title">
                Job Detail: <?= esc($job['job_no']) ?>
            </div>
        </div>
    </div>

    <div class="container">

        <?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">
            <div class="job-header">
                <h1>Job <?= esc($job['job_no']) ?></h1>
                <span class="status <?= esc($statusClass) ?>">
                    <?= esc(ucwords(str_replace('_', ' ', $job['status'] ?? '-'))) ?>
                </span>
            </div>

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

                <div class="label">Job Type</div>
                <div class="value"><?= esc(ucfirst($job['job_type'] ?? '-')) ?></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">Solution Note</div>
                <div class="value"><?= nl2br(esc($job['solution_note'] ?? '-')) ?></div>

                <div class="label">Created At</div>
                <div class="value"><?= esc($job['created_at'] ?? '-') ?></div>

                <div class="label">Closed At</div>
                <div class="value"><?= esc($job['closed_at'] ?? '-') ?></div>
            </div>

            <div class="status-control">
                <form method="POST">
                    <input type="hidden" name="job_id" value="<?= (int)$job_id ?>">
                    <label for="new_status">Change Status</label>
                    <div class="status-row">
                        <select id="new_status" name="new_status">
                            <?php foreach ($allowedStatuses as $statusVal => $statusLabel): ?>
                                <option value="<?= esc($statusVal) ?>" <?= (($job['status'] ?? '') === $statusVal) ? 'selected' : '' ?>>
                                    <?= esc($statusLabel) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
                    </div>
                    <?php if (($job['status'] ?? '') === 'closed'): ?>
                        <p class="help">This job is currently <strong>closed</strong>. Select "Open" and click Update Status to reopen it.</p>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <div class="box">
            <h2>Staff Attachments</h2>

            <?php if ($images): ?>
                <div class="image-list">
                    <?php foreach ($images as $img): ?>
                        <?php
                            $imageUrl = jobImageUrl($img['image_path'] ?? '');
                            $imageFsPath = jobImageFilePath($img['image_path'] ?? '');
                            $imageSize = (is_file($imageFsPath) && file_exists($imageFsPath))
                                ? formatFileSize(filesize($imageFsPath))
                                : '-';
                        ?>
                        <div class="image-card">
                            <?php if ($imageUrl !== ''): ?>
                                <img src="<?= esc($imageUrl) ?>" alt="Job Image">
                                <a class="open-link" href="<?= esc($imageUrl) ?>" target="_blank" rel="noopener noreferrer">
                                    Open full image
                                </a>
                            <?php else: ?>
                                <p class="empty-note">Image path is empty.</p>
                            <?php endif; ?>

                            <div class="cap">
                                <strong>Type:</strong> <?= esc($img['image_type'] ?? '-') ?><br>
                                <strong>Uploaded:</strong> <?= esc($img['created_at'] ?? '-') ?><br>
                                <strong>Size:</strong> <?= esc($imageSize) ?>
                            </div>

                            <form method="POST" class="delete-form"
                                  onsubmit="return confirm('Delete this image permanently? This cannot be undone.');">
                                <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_image" class="btn-delete">Delete image</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-note">No pictures uploaded yet.</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>