<?php
ob_start();
session_start();
require_once '../config/database.php';       // $pdo (Seven Credit DB)
require_once '../config/modules.php';         // company_enabled_modules(), module_on()
require_once '../config/module_access.php';   // mod_can_view(), mod_can_edit()

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php'); exit;
}
$companyId   = (int)$_SESSION['company_id'];
$userId      = (int)$_SESSION['user_id'];
$role        = $_SESSION['role'] ?? '';
$companyName = $_SESSION['company_name'] ?? 'Company';

$enabled = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'jobs')) {
    http_response_code(403);
    exit('The Job Management module is not enabled for your company.');
}
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

// Must at least have view access to the module at all.
if (!mod_can_view($pdo, $companyId, $userId, $role, 'jobs')) {
    http_response_code(403);
    exit('You do not have access to Job Management. Please ask your admin.');
}

$canManage = mod_can_admin($pdo, $companyId, $userId, $role, 'jobs');

$jobId = (int)($_GET['id'] ?? 0);
if ($jobId <= 0) {
    header('Location: ' . ($canManage ? 'sp_jobs_admin.php' : 'sp_jobs_staff.php')); exit;
}

/*
|--------------------------------------------------------------------------
| Helper: pretty job number
|--------------------------------------------------------------------------
*/
function formatJobNoText($jobNo)
{
    $jobNo = (string)$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;
}

/*
|--------------------------------------------------------------------------
| Load the job (scoped by company_id) + customer name + machine model.
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT
        j.*,
        c.customer_name AS customer_name,
        m.machine_model AS machine_model,
        m.serial_no     AS machine_serial_no
    FROM sp_jobs j
    LEFT JOIN sp_customers c ON c.company_id = j.company_id AND c.sd_no = j.sd_no
    LEFT JOIN sp_machines  m ON m.company_id = j.company_id AND m.id = j.machine_id
    WHERE j.company_id = ? AND j.id = ?
    LIMIT 1
");
$stmt->execute([$companyId, $jobId]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$job) {
    http_response_code(404);
    exit('Job not found.');
}

/*
|--------------------------------------------------------------------------
| Assigned staff (join sp_job_staff -> users), scoped by company_id.
| Also used to check if the current user may view (when not a manager).
|--------------------------------------------------------------------------
*/
$assignStmt = $pdo->prepare("
    SELECT js.user_id, u.name AS user_name
    FROM sp_job_staff js
    LEFT JOIN users u ON u.id = js.user_id
    WHERE js.company_id = ? AND js.job_id = ?
    ORDER BY u.name ASC
");
$assignStmt->execute([$companyId, $jobId]);
$assigned = $assignStmt->fetchAll(PDO::FETCH_ASSOC);

$assignedUserIds = array_map(static function ($r) { return (int)$r['user_id']; }, $assigned);
$isAssignedToMe  = in_array($userId, $assignedUserIds, true);

// Access rule: allow if manage OR the job is assigned to this user.
if (!$canManage && !$isAssignedToMe) {
    http_response_code(403);
    exit('You are not assigned to this job.');
}

/*
|--------------------------------------------------------------------------
| Payment type label — resolve from sp_payment_types by code (scoped).
|--------------------------------------------------------------------------
*/
$paymentTypeLabel = (string)($job['payment_type'] ?? '');
if ($paymentTypeLabel !== '') {
    try {
        $plStmt = $pdo->prepare("SELECT label FROM sp_payment_types WHERE company_id = ? AND code = ? LIMIT 1");
        $plStmt->execute([$companyId, $paymentTypeLabel]);
        $lbl = $plStmt->fetchColumn();
        if ($lbl) {
            $paymentTypeLabel = (string)$lbl;
        } else {
            $paymentTypeLabel = ucwords(str_replace('_', ' ', $paymentTypeLabel));
        }
    } catch (Throwable $e) {
        $paymentTypeLabel = ucwords(str_replace('_', ' ', $paymentTypeLabel));
    }
}

/*
|--------------------------------------------------------------------------
| Photo references (scoped by company_id).
|--------------------------------------------------------------------------
*/
// Resolve a stored image path to a usable URL:
//  - Drive proxy paths (drive_file.php?id=..) are served by the local proxy
//  - legacy local files (uploads/..) live in company/uploads OR on the old portal
if (!function_exists('jobImgUrl')) {
    function jobImgUrl($path) {
        $p = trim((string)$path);
        if ($p === '') return '';
        if (preg_match('#^https?://#i', $p)) return $p;
        if (strpos($p, 'drive_file.php') !== false) return $p;
        if (strpos($p, 'uploads/') === 0) {
            if (is_file(__DIR__ . '/' . $p)) return $p;                 // new local file here
            return 'https://7d-lao.com/service-portal/' . $p;           // legacy file on old portal
        }
        return $p;
    }
}

$images = [];
try {
    $imgStmt = $pdo->prepare("SELECT id, image_path, image_type, created_at
                              FROM sp_job_images WHERE company_id = ? AND job_id = ? ORDER BY id ASC");
    $imgStmt->execute([$companyId, $jobId]);
    $images = $imgStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $images = [];
}

$backLink = $canManage ? 'sp_jobs_admin.php' : 'sp_jobs_staff.php';
$statusClass = 'status-' . preg_replace('/[^a-z_]/', '', (string)($job['status'] ?? ''));
$customerDisplay = (($job['customer_name'] ?? '') !== '') ? $job['customer_name'] : ($job['sd_no'] ?: '-');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Job <?= esc(formatJobNoText($job['job_no'] ?? '')) ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #eef2f9;
            --card: #ffffff;
            --ink: #0f172a;
            --muted: #64748b;
            --line: #e6eaf2;
            --brand: #1d4ed8;
            --brand2: #1e40af;
            --hero: linear-gradient(135deg, #1e40af 0%, #172a6b 100%);
            --shadow: 0 12px 30px rgba(30, 41, 59, 0.08);
            --shadow-sm: 0 2px 6px rgba(30, 41, 59, 0.06);
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: 'Noto Sans Lao', 'Inter', Arial, sans-serif;
            background: var(--bg);
            color: var(--ink);
            -webkit-font-smoothing: antialiased;
        }
        .wrap { max-width: 1000px; margin: 0 auto; padding: 24px 16px 48px; }
        .topbar {
            display: flex; align-items: center; justify-content: space-between;
            gap: 16px; flex-wrap: wrap; margin-bottom: 18px;
        }
        .topbar a.back {
            background: #fff; border: 1px solid var(--line); padding: 9px 15px;
            border-radius: 999px; text-decoration: none; color: #475569; font-weight: 600;
            font-size: 14px; transition: all .15s ease; box-shadow: var(--shadow-sm);
        }
        .topbar a.back:hover { color: var(--brand); border-color: #c7d2fe; transform: translateY(-1px); }
        .topbar .company { font-weight: 700; color: var(--muted); font-size: 14px; }

        .card {
            background: var(--card); border: 1px solid var(--line); border-radius: 20px;
            box-shadow: var(--shadow); padding: 24px; margin-bottom: 20px;
        }
        .hero { background: var(--hero); color: #fff; border: none; }
        .job-header {
            display: flex; justify-content: space-between; align-items: flex-start;
            gap: 14px; flex-wrap: wrap;
        }
        .job-header h1 { margin: 0; font-size: 26px; font-weight: 800; letter-spacing: -0.02em; }
        .job-header .sub { margin-top: 6px; font-size: 13px; opacity: .85; font-weight: 600; }
        .status {
            display: inline-block; padding: 7px 14px; border-radius: 999px;
            font-size: 12px; font-weight: 800;
        }
        .status-open        { background: rgba(255,255,255,0.22); color: #fff; }
        .status-assigned    { background: rgba(255,255,255,0.22); color: #fff; }
        .status-in_progress { background: rgba(255,255,255,0.22); color: #fff; }
        .status-closed      { background: #dcfce7; color: #166534; }

        h2 { margin: 0 0 16px; font-size: 18px; font-weight: 800; }
        .info-grid { display: grid; grid-template-columns: 190px 1fr; gap: 12px 18px; }
        .label { font-size: 13px; color: var(--muted); font-weight: 700; }
        .value { font-size: 15px; color: var(--ink); word-break: break-word; }
        .type-badge {
            display: inline-block; background: #ede9fe; color: #6d28d9; padding: 4px 11px;
            border-radius: 999px; font-size: 12px; font-weight: 700;
        }
        .chip {
            display: inline-block; background: #eef2ff; color: var(--brand); padding: 5px 12px;
            border-radius: 999px; font-size: 13px; font-weight: 700; margin: 0 6px 6px 0;
        }
        .img-list { list-style: none; margin: 0; padding: 0; }
        .img-list li {
            padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px;
            background: #f8fafc; margin-bottom: 10px; font-size: 13px; word-break: break-all;
        }
        .img-list .meta { color: var(--muted); font-size: 12px; margin-top: 4px; }
        .img-list a { color: var(--brand); font-weight: 700; text-decoration: none; }
        .img-list a:hover { text-decoration: underline; }
        .empty-note { color: var(--muted); margin: 0; }
        .photo-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 14px; }
        .photo-card { border: 1px solid var(--line, #e6eaf2); border-radius: 12px; overflow: hidden; background: #fff; }
        .photo-card img { width: 100%; height: 160px; object-fit: cover; display: block; }
        .photo-card .meta { color: var(--muted); font-size: 12px; padding: 8px 10px; }
        @media (max-width: 700px) {
            .info-grid { grid-template-columns: 1fr; gap: 4px 0; }
            .info-grid .label { margin-top: 10px; }
            .job-header h1 { font-size: 22px; }
        }
    </style>
</head>
<body>
    <div class="wrap">

        <div class="topbar">
            <a class="back" href="<?= esc($backLink) ?>">&larr; Back to Jobs</a>
            <span class="company"><?= esc($companyName) ?></span>
        </div>

        <div class="card hero">
            <div class="job-header">
                <div>
                    <h1>Job <?= esc(formatJobNoText($job['job_no'] ?? '')) ?></h1>
                    <div class="sub"><?= esc($job['job_no'] ?? '') ?></div>
                </div>
                <span class="status <?= esc($statusClass) ?>">
                    <?= esc(ucwords(str_replace('_', ' ', (string)($job['status'] ?? '-')))) ?>
                </span>
            </div>
        </div>

        <div class="card">
            <h2>Job Details</h2>
            <div class="info-grid">
                <div class="label">Job Type</div>
                <div class="value"><?= esc(($job['job_type'] ?? '') !== '' ? ucwords((string)$job['job_type']) : '-') ?></div>

                <div class="label">Customer</div>
                <div class="value"><?= esc($customerDisplay) ?></div>

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

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

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

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

                <div class="label">Priority</div>
                <div class="value"><?= esc(($job['priority'] ?? '') !== '' ? ucfirst((string)$job['priority']) : '-') ?></div>

                <div class="label">Payment Type</div>
                <div class="value">
                    <?php if ($paymentTypeLabel !== ''): ?>
                        <span class="type-badge"><?= esc($paymentTypeLabel) ?></span>
                    <?php else: ?>
                        -
                    <?php endif; ?>
                </div>

                <div class="label">Staff Fee</div>
                <div class="value"><?= number_format((float)($job['staff_fee'] ?? 0), 0) ?> LAK</div>

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

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

                <div class="label">Assigned Staff</div>
                <div class="value">
                    <?php if ($assigned): ?>
                        <?php foreach ($assigned as $a): ?>
                            <span class="chip"><?= esc(($a['user_name'] ?? '') !== '' ? $a['user_name'] : ('User #' . (int)$a['user_id'])) ?></span>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <span class="empty-note">No staff assigned.</span>
                    <?php endif; ?>
                </div>

                <div class="label">Open Date</div>
                <div class="value"><?= esc($job['open_date'] ?: ($job['created_at'] ?? '-')) ?></div>

                <div class="label">Solution Note</div>
                <div class="value"><?= nl2br(esc($job['solution_note'] ?? '')) ?: '-' ?></div>

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

        <div class="card">
            <h2>Photos <?php if ($images): ?><span style="font-size:13px;color:#64748b;font-weight:600;">(<?= count($images) ?>)</span><?php endif; ?></h2>
            <?php if ($images): ?>
                <div class="photo-grid">
                    <?php foreach ($images as $img): ?>
                        <?php $url = jobImgUrl($img['image_path'] ?? ''); ?>
                        <div class="photo-card">
                            <?php if ($url !== ''): ?>
                                <a href="<?= esc($url) ?>" target="_blank" rel="noopener noreferrer"><img src="<?= esc($url) ?>" alt="Job photo" loading="lazy"></a>
                            <?php else: ?>
                                <div class="empty-note" style="padding:20px;">(no image)</div>
                            <?php endif; ?>
                            <div class="meta"><?= esc($img['created_at'] ?: '-') ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-note">No photos attached.</p>
            <?php endif; ?>
        </div>

    </div>
</body>
</html>
<?php ob_end_flush(); ?>