isLoggedIn()) { throw new Exception('Admin authentication required'); } // Only handle POST requests if ($_SERVER['REQUEST_METHOD'] !== 'POST') { throw new Exception('Only POST requests allowed'); } $admin = $auth->getCurrentAdmin(); $ticketId = isset($_POST['ticket_id']) ? intval($_POST['ticket_id']) : 0; $status = isset($_POST['status']) ? trim($_POST['status']) : ''; // Validate input if ($ticketId <= 0) { throw new Exception('Invalid ticket ID'); } if (empty($status)) { throw new Exception('Status is required'); } $validStatuses = ['open', 'pending', 'resolved', 'closed']; if (!in_array($status, $validStatuses)) { throw new Exception('Invalid status. Must be: ' . implode(', ', $validStatuses)); } // Database update $db = new Database(); $pdo = $db->getConnection(); // Get current ticket info $stmt = $pdo->prepare("SELECT id, ticket_number, status FROM support_tickets WHERE id = ?"); $stmt->execute([$ticketId]); $ticket = $stmt->fetch(); if (!$ticket) { throw new Exception('Ticket not found'); } // Update status $stmt = $pdo->prepare(" UPDATE support_tickets SET status = ?, resolved_at = CASE WHEN ? = 'resolved' THEN NOW() ELSE resolved_at END, updated_at = NOW() WHERE id = ? "); $result = $stmt->execute([$status, $status, $ticketId]); if (!$result || $stmt->rowCount() === 0) { throw new Exception('Failed to update ticket status'); } // Log the success logError('Ticket status updated successfully', [ 'ticket_id' => $ticketId, 'ticket_number' => $ticket['ticket_number'], 'old_status' => $ticket['status'], 'new_status' => $status, 'admin_id' => $admin['id'], 'admin_username' => $admin['username'] ]); // Return success echo json_encode([ 'success' => true, 'message' => 'Status updated successfully', 'ticket_id' => $ticketId, 'ticket_number' => $ticket['ticket_number'], 'old_status' => $ticket['status'], 'new_status' => $status, 'updated_by' => $admin['full_name'] ]); } catch (Exception $e) { // Return error echo json_encode([ 'success' => false, 'message' => $e->getMessage(), 'debug_info' => [ 'ticket_id' => $ticketId ?? 'not_provided', 'status' => $status ?? 'not_provided', 'admin_logged_in' => $auth->isLoggedIn(), 'request_method' => $_SERVER['REQUEST_METHOD'] ] ]); } ?>