<?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('Job Management is not enabled for your company.');
}
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

/*
|--------------------------------------------------------------------------
| Pretty job number (JOB-YYYYMMDDHHMMSS -> dd/mm/YYYY (HHMMSS))
|--------------------------------------------------------------------------
*/
function formatJobNo($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 . ' <span class="job-time">(' . $time . ')</span>';
    }
    return $jobNo;
}

/*
|--------------------------------------------------------------------------
| Load the job (scoped by company_id)
|--------------------------------------------------------------------------
*/
$jobId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$job   = null;
if ($jobId > 0) {
    $st = $pdo->prepare("SELECT * FROM sp_jobs WHERE id = ? AND company_id = ? LIMIT 1");
    $st->execute([$jobId, $companyId]);
    $job = $st->fetch(PDO::FETCH_ASSOC);
}
if (!$job) {
    http_response_code(404);
    exit('Job not found.');
}

/*
|--------------------------------------------------------------------------
| Access: managers only (Manage access on the jobs module).
|--------------------------------------------------------------------------
*/
$canManage = mod_can_admin($pdo, $companyId, $userId, $role, 'jobs');
if (!$canManage) {
    http_response_code(403);
    exit('You need Manage (admin) access to edit jobs.');
}

$message = '';
$error   = '';

/*
|--------------------------------------------------------------------------
| Load customers for this company
|--------------------------------------------------------------------------
*/
$customers = [];
try {
    $cs = $pdo->prepare("SELECT id, sd_no, customer_name, telephone
                         FROM sp_customers WHERE company_id = ?
                         ORDER BY customer_name ASC, sd_no ASC");
    $cs->execute([$companyId]);
    $customers = $cs->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $error = 'Could not load customers: ' . $e->getMessage(); }

/*
|--------------------------------------------------------------------------
| Load machines for this company (used for select + JS filter by sd_no)
|--------------------------------------------------------------------------
*/
$machines = [];
try {
    $ms = $pdo->prepare("SELECT id, sd_no, unique_machine_no, machine_model, serial_no, location_text
                         FROM sp_machines WHERE company_id = ?
                         ORDER BY unique_machine_no ASC");
    $ms->execute([$companyId]);
    $machines = $ms->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { if ($error === '') $error = 'Could not load machines: ' . $e->getMessage(); }

/*
|--------------------------------------------------------------------------
| Load payment types for this company
|--------------------------------------------------------------------------
*/
$paymentTypes = [];
try {
    $ps = $pdo->prepare("SELECT code, label, fee, is_manual_fee
                         FROM sp_payment_types WHERE company_id = ? AND status = 'active'
                         ORDER BY sort_order ASC, label ASC");
    $ps->execute([$companyId]);
    $paymentTypes = $ps->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { /* payment types optional */ }
$validPaymentCodes = array_column($paymentTypes, 'code');

/*
|--------------------------------------------------------------------------
| Load assignable staff (this company's users via company_staff -> users)
|--------------------------------------------------------------------------
*/
$staffList = [];
try {
    $ss = $pdo->prepare("SELECT u.id, u.name, cs.staff_code
                         FROM company_staff cs JOIN users u ON u.id = cs.user_id
                         WHERE cs.company_id = ? ORDER BY u.name ASC");
    $ss->execute([$companyId]);
    $staffList = $ss->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { /* staff optional */ }
$validStaffIds = array_map('intval', array_column($staffList, 'id'));

/*
|--------------------------------------------------------------------------
| Currently assigned staff for this job
|--------------------------------------------------------------------------
*/
$assignedStaffIds = [];
try {
    $as = $pdo->prepare("SELECT user_id FROM sp_job_staff WHERE company_id = ? AND job_id = ?");
    $as->execute([$companyId, $jobId]);
    $assignedStaffIds = array_map('intval', array_column($as->fetchAll(PDO::FETCH_ASSOC), 'user_id'));
} catch (Throwable $e) { $assignedStaffIds = []; }

/*
|--------------------------------------------------------------------------
| Handle update (manage-gated above)
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $machine_id        = (int)($_POST['machine_id'] ?? 0);
    $issue_title       = trim($_POST['issue_title'] ?? '');
    $issue_description = trim($_POST['issue_description'] ?? '');
    $job_type          = trim($_POST['job_type'] ?? ($job['job_type'] ?? 'machine'));
    $priority          = trim($_POST['priority'] ?? 'medium');
    $payment_type      = trim($_POST['payment_type'] ?? '');
    $status            = trim($_POST['status'] ?? 'open');

    $staff_fee_raw = isset($_POST['staff_fee']) ? str_replace(',', '', trim($_POST['staff_fee'])) : '';
    $staff_fee     = ($staff_fee_raw !== '' && is_numeric($staff_fee_raw)) ? (float)$staff_fee_raw : 0;

    $assigned_staff_ids = $_POST['assigned_staff_ids'] ?? [];
    if (!is_array($assigned_staff_ids)) $assigned_staff_ids = [];
    $assigned_staff_ids = array_values(array_unique(array_filter(
        array_map('intval', $assigned_staff_ids),
        fn($id) => $id > 0 && in_array($id, $validStaffIds, true)
    )));

    // Resolve + validate the machine (must belong to this company)
    $machineRow = null;
    if ($machine_id > 0) {
        $mchk = $pdo->prepare("SELECT id, sd_no, unique_machine_no
                               FROM sp_machines WHERE id = ? AND company_id = ? LIMIT 1");
        $mchk->execute([$machine_id, $companyId]);
        $machineRow = $mchk->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    if (!$machineRow) {
        $error = 'Please select a valid machine.';
    } elseif ($issue_title === '') {
        $error = 'Issue title is required.';
    } elseif (!in_array($priority, ['low', 'medium', 'high', 'urgent'], true)) {
        $error = 'Invalid priority.';
    } elseif (!in_array($status, ['open', 'assigned', 'in_progress', 'closed'], true)) {
        $error = 'Invalid status.';
    } elseif ($payment_type !== '' && !in_array($payment_type, $validPaymentCodes, true)) {
        $error = 'Invalid payment type.';
    }

    if ($error === '') {
        // Auto-bump to "assigned" if staff selected and still open
        if (count($assigned_staff_ids) > 0 && $status === 'open') {
            $status = 'assigned';
        }

        $sd_no      = $machineRow['sd_no'] ?? null;
        $machine_no = $machineRow['unique_machine_no'] ?? null;

        try {
            $pdo->beginTransaction();

            $upd = $pdo->prepare("
                UPDATE sp_jobs SET
                    job_type          = ?,
                    sd_no             = ?,
                    machine_id        = ?,
                    machine_no        = ?,
                    issue_title       = ?,
                    issue_description = ?,
                    priority          = ?,
                    payment_type      = ?,
                    staff_fee         = ?,
                    status            = ?,
                    closed_at         = CASE WHEN ? = 'closed' THEN COALESCE(closed_at, NOW()) ELSE NULL END
                WHERE id = ? AND company_id = ?
            ");
            $upd->execute([
                $job_type, $sd_no, $machine_id, $machine_no,
                $issue_title, $issue_description, $priority, $payment_type, $staff_fee,
                $status, $status, $jobId, $companyId
            ]);

            // Replace assigned staff rows for this job
            $del = $pdo->prepare("DELETE FROM sp_job_staff WHERE company_id = ? AND job_id = ?");
            $del->execute([$companyId, $jobId]);

            if (!empty($assigned_staff_ids)) {
                $ins = $pdo->prepare("INSERT INTO sp_job_staff (company_id, job_id, user_id) VALUES (?, ?, ?)");
                foreach ($assigned_staff_ids as $uid) {
                    $ins->execute([$companyId, $jobId, $uid]);
                }
            }

            $pdo->commit();
            header('Location: sp_jobs_admin.php'); exit;

        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $error = 'Error updating job: ' . $e->getMessage();
        }
    }

    // Repopulate form values on error
    $job['job_type']          = $job_type;
    $job['sd_no']             = $machineRow['sd_no'] ?? ($job['sd_no'] ?? '');
    $job['machine_id']        = $machine_id;
    $job['issue_title']       = $issue_title;
    $job['issue_description'] = $issue_description;
    $job['priority']          = $priority;
    $job['payment_type']      = $payment_type;
    $job['staff_fee']         = $staff_fee;
    $job['status']            = $status;
    $assignedStaffIds         = $assigned_staff_ids;
}

// Current customer sd_no for pre-selecting the customer dropdown
$currentSdNo = (string)($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>Edit Job - Service Portal</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>
        * { box-sizing: border-box; }
        body {
            font-family: 'Noto Sans Lao', 'Inter', Arial, sans-serif;
            background: #f3f6fb; margin: 0; color: #111827;
            -webkit-font-smoothing: antialiased;
        }
        .sp-topbar {
            background: #0f172a; color: #fff; padding: 14px 22px;
            display: flex; justify-content: space-between; align-items: center;
            flex-wrap: wrap; gap: 10px;
        }
        .sp-topbar .brand { font-size: 18px; font-weight: 700; }
        .sp-topbar .who { color: #93c5fd; font-size: 14px; font-weight: 600; }

        .container { max-width: 1000px; margin: 24px auto; padding: 0 16px; }
        .nav-links { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 22px; }
        .nav-links a {
            background: #fff; border: 1px solid #dbe3ee; padding: 10px 14px;
            border-radius: 10px; text-decoration: none; color: #1f2937; font-weight: bold;
        }
        .nav-links a:hover { background: #eff6ff; }
        .nav-links a.active { background: #2563eb; color: #fff; border-color: #2563eb; }

        .back-row { margin-bottom: 16px; }
        .back-btn {
            display: inline-block; background: #2563eb; color: #fff; padding: 8px 14px;
            border-radius: 8px; text-decoration: none; font-weight: bold;
        }
        .back-btn:hover { background: #1d4ed8; }

        .job-box {
            background: #fff; padding: 24px; border-radius: 16px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
        }
        .job-title { margin-top: 0; margin-bottom: 16px; font-size: 24px; font-weight: 700; }
        .job-time { font-weight: 500; color: #6b7280; }

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

        .job-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .job-full { grid-column: 1 / -1; }
        .job-form-group label { font-weight: bold; display: block; margin-bottom: 6px; }
        .job-form-group input, .job-form-group select, .job-form-group textarea {
            width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 10px;
            margin-top: 4px; font-size: 14px; background: #fff; color: #111827; font-family: inherit;
        }
        .job-form-group textarea { min-height: 120px; resize: vertical; }

        .job-submit-btn {
            margin-top: 8px; padding: 12px 20px; background: #2563eb; color: #fff;
            border: none; border-radius: 10px; cursor: pointer; font-weight: bold;
        }
        .job-submit-btn:hover { background: #1d4ed8; }

        .staff-list { border: 1px solid #e5e7eb; border-radius: 10px; padding: 12px; max-height: 220px; overflow-y: auto; }
        .staff-list label { font-weight: normal; display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
        .staff-list label:last-child { margin-bottom: 0; }
        .staff-list input[type="checkbox"] { width: auto; margin: 0; }

        @media (max-width: 768px) { .job-grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
    <div class="sp-topbar">
        <div class="brand">Seven Digital &mdash; Service Portal</div>
        <div class="who">Welcome, <?= esc($companyName) ?></div>
    </div>

    <div class="container">

        <div class="nav-links">
            <a href="sp_jobs_admin.php">Dashboard</a>
            <a href="sp_job_add.php">Open Job</a>
            <a href="../company/staff.php">Staff</a>
            <a href="sp_staff_payments.php">Staff Payment</a>
            <a href="sp_payment_types.php">Payment Types</a>
            <a href="dashboard.php">Back to Company</a>
            <a href="../auth/logout.php">Logout</a>
        </div>

        <div class="back-row">
            <a href="sp_jobs_admin.php" class="back-btn">&larr; Back</a>
        </div>

        <div class="job-box">
            <h2 class="job-title">Edit Job: <?= formatJobNo($job['job_no'] ?? '') ?></h2>

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

            <form method="POST">
                <input type="hidden" name="id" value="<?= (int)$jobId ?>">

                <div class="job-grid">

                    <div class="job-form-group">
                        <label>Customer *</label>
                        <select id="customer_select" onchange="filterMachines()" required>
                            <option value="">Select customer</option>
                            <?php foreach ($customers as $c): ?>
                                <?php
                                    $label = ($c['customer_name'] ?? '') !== '' ? $c['customer_name'] : ('SD ' . ($c['sd_no'] ?? ''));
                                    $sel = ($currentSdNo !== '' && (string)($c['sd_no'] ?? '') === $currentSdNo) ? 'selected' : '';
                                ?>
                                <option value="<?= esc($c['sd_no']) ?>" <?= $sel ?>>
                                    <?= esc($label) ?> (<?= esc($c['sd_no']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Machine *</label>
                        <select name="machine_id" id="machine_select" required>
                            <option value="">Select customer first</option>
                        </select>
                    </div>

                    <div class="job-form-group job-full">
                        <label>Issue Title *</label>
                        <input type="text" name="issue_title" value="<?= esc($job['issue_title'] ?? '') ?>" required>
                    </div>

                    <div class="job-form-group job-full">
                        <label>Issue Description</label>
                        <textarea name="issue_description"><?= esc($job['issue_description'] ?? '') ?></textarea>
                    </div>

                    <div class="job-form-group">
                        <label>Job Type</label>
                        <select name="job_type">
                            <?php
                                $jt = $job['job_type'] ?? 'machine';
                                $jtOptions = ['machine' => 'Machine', 'general' => 'General', 'setup' => 'Setup'];
                                if ($jt !== '' && !isset($jtOptions[$jt])) {
                                    $jtOptions[$jt] = ucwords(str_replace('_', ' ', $jt));
                                }
                            ?>
                            <?php foreach ($jtOptions as $val => $lbl): ?>
                                <option value="<?= esc($val) ?>" <?= $jt === $val ? 'selected' : '' ?>><?= esc($lbl) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Priority *</label>
                        <select name="priority" required>
                            <?php $pr = $job['priority'] ?? 'medium'; ?>
                            <option value="medium" <?= $pr === 'medium' ? 'selected' : '' ?>>Medium</option>
                            <option value="low"    <?= $pr === 'low' ? 'selected' : '' ?>>Low</option>
                            <option value="high"   <?= $pr === 'high' ? 'selected' : '' ?>>High</option>
                            <option value="urgent" <?= $pr === 'urgent' ? 'selected' : '' ?>>Urgent</option>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Payment Type</label>
                        <select name="payment_type">
                            <option value="">Select</option>
                            <?php foreach ($paymentTypes as $pt): ?>
                                <option value="<?= esc($pt['code']) ?>" <?= (($job['payment_type'] ?? '') === $pt['code']) ? 'selected' : '' ?>>
                                    <?= esc($pt['label']) ?>
                                    <?= empty($pt['is_manual_fee']) ? ' (' . esc(number_format((float)$pt['fee'], 0)) . ')' : '' ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Status *</label>
                        <select name="status" required>
                            <?php $stt = $job['status'] ?? 'open'; ?>
                            <option value="open"        <?= $stt === 'open' ? 'selected' : '' ?>>Open</option>
                            <option value="assigned"    <?= $stt === 'assigned' ? 'selected' : '' ?>>Assigned</option>
                            <option value="in_progress" <?= $stt === 'in_progress' ? 'selected' : '' ?>>In Progress</option>
                            <option value="closed"      <?= $stt === 'closed' ? 'selected' : '' ?>>Closed</option>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Staff Fee</label>
                        <input type="number" name="staff_fee" min="0" step="0.01"
                               value="<?= esc($job['staff_fee'] ?? '') ?>">
                    </div>

                    <div class="job-form-group job-full">
                        <label>Assign Staff</label>
                        <div class="staff-list">
                            <?php if ($staffList): ?>
                                <?php foreach ($staffList as $s): ?>
                                    <label>
                                        <input type="checkbox" name="assigned_staff_ids[]"
                                               value="<?= (int)$s['id'] ?>"
                                               <?= in_array((int)$s['id'], $assignedStaffIds, true) ? 'checked' : '' ?>>
                                        <?= esc($s['name']) ?><?= ($s['staff_code'] ?? '') !== '' ? ' (' . esc($s['staff_code']) . ')' : '' ?>
                                    </label>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <span style="color:#6b7280;">No company staff available.</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="job-form-group job-full">
                        <button type="submit" class="job-submit-btn">Update Job</button>
                    </div>

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

    <script>
        const machineData = <?= json_encode(array_map(function ($m) {
            return [
                'id'         => (int)$m['id'],
                'sd_no'      => $m['sd_no'] ?? '',
                'machine_no' => $m['unique_machine_no'] ?? '',
                'model'      => $m['machine_model'] ?? '',
            ];
        }, $machines), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

        const currentMachineId = <?= json_encode((int)($job['machine_id'] ?? 0)) ?>;

        function escapeHtml(str) {
            return String(str ?? '')
                .replace(/&/g, '&amp;').replace(/</g, '&lt;')
                .replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
        }

        function filterMachines() {
            const sd  = document.getElementById('customer_select').value;
            const sel = document.getElementById('machine_select');
            const list = machineData.filter(m => String(m.sd_no) === String(sd));

            if (!sd) {
                sel.innerHTML = '<option value="">Select customer first</option>';
                return;
            }
            if (!list.length) {
                sel.innerHTML = '<option value="">No machines for this customer</option>';
                return;
            }
            let html = '<option value="">Select machine</option>';
            list.forEach(m => {
                const text  = (m.machine_no || '-') + ' - ' + (m.model || '');
                const isSel = Number(m.id) === Number(currentMachineId) ? ' selected' : '';
                html += '<option value="' + m.id + '"' + isSel + '>' + escapeHtml(text) + '</option>';
            });
            sel.innerHTML = html;
        }

        document.addEventListener('DOMContentLoaded', function () {
            // Pre-select this job's customer + machine on load
            filterMachines();
        });
    </script>
</body>
</html>
<?php ob_end_flush(); ?>