<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('technician_panel');

$pdo = getDB();
$user = currentUser();
$user_id = $user['id'];
$is_admin = in_array($user['role_name'], ['Super Admin', 'Admin']);

$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$job_id) {
    $_SESSION['error'] = 'Invalid job ID.';
    header('Location: technician_panel.php'); exit;
}

// Fetch job with permission check
if ($is_admin) {
    $stmt = $pdo->prepare("SELECT rj.*, c.name as customer_name, c.phone as customer_phone FROM repair_jobs rj LEFT JOIN customers c ON rj.customer_id = c.id WHERE rj.id=?");
    $stmt->execute([$job_id]);
} else {
    $stmt = $pdo->prepare("SELECT rj.*, c.name as customer_name, c.phone as customer_phone FROM repair_jobs rj LEFT JOIN customers c ON rj.customer_id = c.id WHERE rj.id=? AND rj.assigned_technician_id=?");
    $stmt->execute([$job_id, $user_id]);
}
$job = $stmt->fetch();

if (!$job) {
    $_SESSION['error'] = 'Job not found or not assigned to you.';
    header('Location: technician_panel.php'); exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $new_status = $_POST['status'];
    $notes = trim($_POST['status_notes']);

    $pdo->prepare("UPDATE repair_jobs SET repair_status=? WHERE id=?")->execute([$new_status, $job_id]);
    $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, new_status, note, changed_by) VALUES (?,?,?,?)")
         ->execute([$job_id, $new_status, $notes, $user_id]);

    logActivity('Updated Repair Status', 'Repairs', $job_id, "Status: $new_status");
    $_SESSION['success'] = 'Job status updated successfully.';
    header('Location: technician_panel.php'); exit;
}

include BASE_PATH . 'includes/header.php';
include BASE_PATH . 'includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-check-circle me-2"></i>Update Job Status</h4>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div><?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h5 class="card-title"><?= htmlspecialchars($job['job_no']) ?> — <?= htmlspecialchars($job['customer_name'] ?? 'Unknown') ?></h5>
            </div>
            <div class="card-body">
                <div class="row mb-4">
                    <div class="col-md-3"><strong>Device:</strong> <?= htmlspecialchars($job['device_brand'] ?? '') ?> <?= htmlspecialchars($job['device_model'] ?? '') ?></div>
                    <div class="col-md-3"><strong>IMEI:</strong> <code><?= htmlspecialchars($job['device_imei'] ?? '-') ?></code></div>
                    <div class="col-md-3"><strong>Current Status:</strong> <?= getStatusBadge($job['repair_status']) ?></div>
                    <div class="col-md-3"><strong>Priority:</strong> <?= ($job['priority'] ?? '') === 'Urgent' ? '<span class="badge bg-danger">Urgent</span>' : '<span class="badge bg-secondary">Normal</span>' ?></div>
                </div>

                <form method="POST">
                    <input type="hidden" name="update_status" value="1">
                    <div class="mb-3">
                        <label class="form-label">New Status</label>
                        <select name="status" class="form-select">
                            <option value="Received" <?= $job['repair_status'] == 'Received' ? 'selected' : '' ?>>Received</option>
                            <option value="Checking" <?= $job['repair_status'] == 'Checking' ? 'selected' : '' ?>>Checking</option>
                            <option value="Waiting for Customer Approval" <?= $job['repair_status'] == 'Waiting for Customer Approval' ? 'selected' : '' ?>>Waiting for Customer Approval</option>
                            <option value="Waiting for Parts" <?= $job['repair_status'] == 'Waiting for Parts' ? 'selected' : '' ?>>Waiting for Parts</option>
                            <option value="Repairing" <?= $job['repair_status'] == 'Repairing' ? 'selected' : '' ?>>Repairing</option>
                            <option value="Completed" <?= $job['repair_status'] == 'Completed' ? 'selected' : '' ?>>Completed</option>
                            <option value="Delivered" <?= $job['repair_status'] == 'Delivered' ? 'selected' : '' ?>>Delivered</option>
                            <option value="Cancelled" <?= $job['repair_status'] == 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
                            <option value="Cannot Repair" <?= $job['repair_status'] == 'Cannot Repair' ? 'selected' : '' ?>>Cannot Repair</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="status_notes" class="form-control" rows="3" placeholder="Optional notes about this status change"></textarea>
                    </div>
                    <div class="mb-3">
                        <a href="technician_panel.php" class="btn btn-secondary">Cancel</a>
                        <button type="submit" class="btn btn-primary">Update Status</button>
                    </div>
                </form>

                <hr>
                <h6>Status History</h6>
                <?php
                $hist = $pdo->prepare("SELECT h.*, u.name as changed_by_name FROM repair_job_status_history h LEFT JOIN users u ON h.changed_by = u.id WHERE h.repair_job_id = ? ORDER BY h.created_at DESC");
                $hist->execute([$job_id]);
                $history = $hist->fetchAll();
                ?>
                <?php if (count($history) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-sm no-datatable">
                        <thead><tr><th>Date</th><th>Status</th><th>Notes</th><th>Changed By</th></tr></thead>
                        <tbody>
                            <?php foreach ($history as $h): ?>
                            <tr>
                                <td><?= formatDateTime($h['created_at']) ?></td>
                                <td><?= getStatusBadge($h['new_status']) ?></td>
                                <td><?= htmlspecialchars($h['note'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($h['changed_by_name'] ?? 'System') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <p class="text-muted">No status history available.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php include BASE_PATH . 'includes/footer.php'; ?>
