<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

$ticket_id = intval($_POST['ticket_id']);
$new_status = $_POST['status'];
$new_priority = $_POST['priority'];
$internal_notes = trim($_POST['internal_notes'] ?? '');
$user_id = $_SESSION['user_id'];

// Debug statements
error_log("Ticket ID: $ticket_id");
error_log("New Status: $new_status");
error_log("New Priority: $new_priority");
error_log("Internal Notes: $internal_notes");
error_log("User ID: $user_id");

try {
    $conn->begin_transaction();

    // Get current state
    $stmt = $conn->prepare("SELECT status, priority FROM support_tickets WHERE ticket_id = ?");
    $stmt->bind_param('i', $ticket_id);
    $stmt->execute();
    $current = $stmt->get_result()->fetch_assoc();

    // Update ticket
    $stmt = $conn->prepare("UPDATE support_tickets SET status = ?, priority = ?, internal_notes = ?, updated_at = NOW() WHERE ticket_id = ?");
    if (!$stmt) {
        throw new Exception($conn->error);
    }
    $stmt->bind_param('sssi', $new_status, $new_priority, $internal_notes, $ticket_id);
    if (!$stmt->execute()) {
        throw new Exception($stmt->error);
    }

    // Log status change
    if ($current['status'] !== $new_status) {
        $stmt = $conn->prepare("INSERT INTO ticket_activity_log (ticket_id, user_id, description) VALUES (?, ?, ?)");
        $description = "Status changed from {$current['status']} to {$new_status}";
        $stmt->bind_param('iis', $ticket_id, $user_id, $description);
        $stmt->execute();
    }

    // Log priority change
    if ($current['priority'] !== $new_priority) {
        $stmt = $conn->prepare("INSERT INTO ticket_activity_log (ticket_id, user_id, description) VALUES (?, ?, ?)");
        $description = "Priority changed from {$current['priority']} to {$new_priority}";
        $stmt->bind_param('iis', $ticket_id, $user_id, $description);
        $stmt->execute();
    }

    $conn->commit();
    $_SESSION['success_alert'] = [
        'title' => 'Success',
        'text' => 'Ticket updated successfully',
        'icon' => 'success'
    ];

    // Debug statement to confirm session alert is set
    error_log("Session alert set: " . print_r($_SESSION['success_alert'], true));

} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['success_alert'] = [
        'title' => 'Error',
        'text' => $e->getMessage(),
        'icon' => 'error'
    ];

    // Debug statement to confirm session alert is set
    error_log("Session alert set: " . print_r($_SESSION['success_alert'], true));
}

$conn->close();
header("Location: view_ticket.php?id=$ticket_id");
exit;
?>
