<?php
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';

requirePermission('trade_jobs.manage');

$companyId = $_SESSION['company_id'] ?? null;
$userId    = $_SESSION['user_id'] ?? null;

if (!$companyId) {
    die("Company isolation error.");
}

$jobId = $_GET['id'] ?? null;

if (!$jobId) {
    die("Invalid job ID.");
}

/* ===============================
   FETCH JOB (Company Isolated)
=================================*/
$stmt = $pdo->prepare("
    SELECT * FROM trade_jobs 
    WHERE id = ? AND company_id = ?
    LIMIT 1
");
$stmt->execute([$jobId, $companyId]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$job) {
    die("Job not found or access denied.");
}

/* ===============================
   HARD LOCK COMPLETED / CANCELLED
=================================*/
if (in_array($job['status'], ['COMPLETED','CANCELLED'])) {
    die("This job is locked and cannot be modified.");
}

/* ===============================
   FETCH INSTALLERS
=================================*/
$stmtUsers = $pdo->prepare("
    SELECT id, full_name 
    FROM users 
    WHERE company_id = ?
    AND status = 'ACTIVE'
    ORDER BY full_name ASC
");
$stmtUsers->execute([$companyId]);
$installers = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);

$error = null;

/* ===============================
   HANDLE UPDATE
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $status      = $_POST['status'] ?? $job['status'];
    $priority    = $_POST['priority'] ?? $job['priority'];
    $assignedId  = $_POST['assigned_user_id'] ?? null;
    $notes       = $_POST['completion_notes'] ?? null;

    /* ===============================
       STATUS WORKFLOW VALIDATION
    =================================*/
    $currentStatus = $job['status'];
    $newStatus = $status;

    $allowedTransitions = [
        'PENDING'   => ['ASSIGNED','CANCELLED'],
        'ASSIGNED'  => ['ON_SITE','CANCELLED'],
        'ON_SITE'   => ['COMPLETED','CANCELLED'],
    ];

    if ($newStatus !== $currentStatus) {
        if (!isset($allowedTransitions[$currentStatus]) ||
            !in_array($newStatus, $allowedTransitions[$currentStatus])) {

            $error = "Invalid status transition.";
        }
    }

    $completedAt = null;
    if ($status === 'COMPLETED') {
        $completedAt = date('Y-m-d H:i:s');
    }

    if (!$error) {

        try {

            $stmtUpdate = $pdo->prepare("
                UPDATE trade_jobs SET
                    status = ?,
                    priority = ?,
                    assigned_user_id = ?,
                    completion_notes = ?,
                    completed_at = ?,
                    updated_at = NOW()
                WHERE id = ? AND company_id = ?
            ");

            $stmtUpdate->execute([
                $status,
                $priority,
                $assignedId ?: null,
                $notes,
                $completedAt,
                $jobId,
                $companyId
            ]);

            /* ===== AUDIT LOG ===== */
            $stmtLog = $pdo->prepare("
                INSERT INTO audit_logs 
                (user_id, action, entity_type, entity_id, ip_address)
                VALUES (?, ?, ?, ?, ?)
            ");

            $stmtLog->execute([
                $userId,
                'UPDATED_TRADE_JOB',
                'trade_jobs',
                $jobId,
                $_SERVER['REMOTE_ADDR'] ?? null
            ]);

            header("Location: view.php?id=" . $jobId);
            exit;

        } catch (PDOException $e) {
            $error = "Update failed: " . $e->getMessage();
        }

    }
}

require_once __DIR__ . '/../../includes/header.php';
require_once __DIR__ . '/../../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>Update Trade Job</h2>
        <p class="page-subtitle">
            <?= htmlspecialchars($job['job_number']) ?> • 
            <?= htmlspecialchars($job['title']) ?>
        </p>
    </div>

    <?php if ($error): ?>
        <div class="alert-danger">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <div class="card">

        <form method="POST">

            <div class="form-group">
                <label>Status</label>
                <select name="status" class="form-control">
                    <?php
                    $statuses = ['PENDING','ASSIGNED','ON_SITE','COMPLETED','CANCELLED'];
                    foreach ($statuses as $s):
                    ?>
                        <option value="<?= $s ?>" <?= $job['status'] === $s ? 'selected' : '' ?>>
                            <?= $s ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Priority</label>
                <select name="priority" class="form-control">
                    <?php
                    $priorities = ['LOW','MEDIUM','HIGH','URGENT'];
                    foreach ($priorities as $p):
                    ?>
                        <option value="<?= $p ?>" <?= $job['priority'] === $p ? 'selected' : '' ?>>
                            <?= $p ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Assign Installer</label>
                <select name="assigned_user_id" class="form-control">
                    <option value="">Unassigned</option>
                    <?php foreach ($installers as $inst): ?>
                        <option value="<?= $inst['id'] ?>"
                            <?= $job['assigned_user_id'] == $inst['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($inst['full_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Completion Notes</label>
                <textarea 
                    name="completion_notes" 
                    rows="4" 
                    class="form-control"
                ><?= htmlspecialchars($job['completion_notes'] ?? '') ?></textarea>
            </div>

            <div style="margin-top:20px;">
                <button type="submit" class="btn-primary">
                    Save Changes
                </button>

                <a href="view.php?id=<?= $jobId ?>" class="btn-secondary">
                    Cancel
                </a>
            </div>

        </form>

    </div>

</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>