<?php
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if we have the necessary parameters
$ticket_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$new_status = $_GET['status'] ?? '';

// Validate inputs
if (!$ticket_id) {
    $_SESSION['error_message'] = "Invalid ticket ID.";
    header("Location: tickets.php");
    exit();
}

if (!in_array($new_status, ['open', 'in_progress', 'closed'])) {
    $_SESSION['error_message'] = "Invalid status value.";
    header("Location: tickets.php");
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Begin transaction
    $db->beginTransaction();
    
    // Get the current status
    $stmt = $db->prepare("SELECT status FROM tickets WHERE id = ?");
    $stmt->execute([$ticket_id]);
    $current_status = $stmt->fetchColumn();
    
    if ($current_status === false) {
        throw new Exception("Ticket not found.");
    }
    
    // If the status is already the same, no need to update
    if ($current_status === $new_status) {
        $_SESSION['info_message'] = "Ticket is already marked as " . ucfirst(str_replace('_', ' ', $new_status)) . ".";
        header("Location: ticket_details.php?id=" . $ticket_id);
        exit();
    }
    
    // Update the ticket status
    $stmt = $db->prepare("UPDATE tickets SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$new_status, $ticket_id]);
    
    // Add a system message about the status change
    $system_message = "Ticket status changed to " . ucfirst(str_replace('_', ' ', $new_status)) . ".";
    
    // Get admin user ID
    $admin_user_id = $_SESSION['user_id'] ?? null;
    
    // If we don't have a valid user ID in the session, try to find an admin user
    if (!$admin_user_id) {
        $stmt = $db->prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1");
        $stmt->execute();
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($admin) {
            $admin_user_id = $admin['id'];
        } else {
            // Get the ticket's user_id as a fallback
            $stmt = $db->prepare("SELECT user_id FROM tickets WHERE id = ?");
            $stmt->execute([$ticket_id]);
            $admin_user_id = $stmt->fetchColumn();
        }
    }
    
    // Insert the system message
    $stmt = $db->prepare("
        INSERT INTO ticket_messages (ticket_id, sender_id, is_admin, message, created_at) 
        VALUES (?, ?, 1, ?, NOW())
    ");
    $stmt->execute([$ticket_id, $admin_user_id, $system_message]);
    
    // Get the user_id for notification
    $stmt = $db->prepare("SELECT user_id FROM tickets WHERE id = ?");
    $stmt->execute([$ticket_id]);
    $user_id = $stmt->fetchColumn();
    
    // Create a notification for the user
    $notification_title = "Ticket Status Updated";
    $notification_message = "Your ticket #$ticket_id has been updated to: " . ucfirst(str_replace('_', ' ', $new_status));
    $notification_link = "ticket_details.php?id=$ticket_id";
    
    $stmt = $db->prepare("
        INSERT INTO notifications (user_id, type, title, message, link, created_at)
        VALUES (?, 'ticket_update', ?, ?, ?, NOW())
    ");
    $stmt->execute([$user_id, $notification_title, $notification_message, $notification_link]);
    
    // Commit the transaction
    $db->commit();
    
    // Set success message
    $_SESSION['success_message'] = "Ticket status has been updated to " . ucfirst(str_replace('_', ' ', $new_status)) . ".";
    
    // Redirect back to the ticket details page
    header("Location: ticket_details.php?id=" . $ticket_id);
    exit();
    
} catch (Exception $e) {
    // Rollback the transaction on error
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    
    $_SESSION['error_message'] = "Failed to update ticket status: " . $e->getMessage();
    header("Location: tickets.php");
    exit();
}
?>
