<?php

// Database connection
require "../../../../database/conn.php";
global $conn;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header('Content-Type: application/json');

// Centralized Input Validation
validate_inputs($_GET, ['student_id', 'action']);

function sendResponse($httpCode, $status, $message, $data = null) {
    global $conn;
    http_response_code($httpCode);
    echo json_encode([
        'code'    => $httpCode,
        'status'  => $status,
        'message' => $message,
        'data'    => $data,
    ]);
    $conn->close();
    exit();
}

// Validate inputs
function validate_inputs(array $data, array $requiredFields) {
    foreach ($requiredFields as $field) {
        if (!isset($data[$field]) || trim($data[$field]) === "") {
            sendResponse(400, "error", "'$field' is missing or empty.");
        }
    }
}

function fetch_tickets($email) {
    global $conn;
    // Prepare the SQL query
    $query = "SELECT `id`, `category`, `issue`, `phone`, `ticket_date`, `img`, `feedback`, `status`, `action` 
              FROM `tickets` WHERE `member_email` = ?";
    
    // Prepare the statement
    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        error_log("Query preparation failed: " . mysqli_error($conn));
        return null; // Return null on preparation error
    }
    
    // Bind the parameter
    if (!mysqli_stmt_bind_param($stmt, 's', $email)) {
        error_log("Parameter binding failed: " . mysqli_error($conn));
        return null; // Return null on binding error
    }
    
    // Execute the statement
    if (!mysqli_stmt_execute($stmt)) {
        error_log("Query execution failed: " . mysqli_error($conn));
        return null; // Return null on execution error
    }
    
    // Fetch the results
    $result = mysqli_stmt_get_result($stmt);
    if (!$result) {
        error_log("Fetching results failed: " . mysqli_error($conn));
        return null; // Return null if fetching results fails
    }
    
    // Store the tickets in an array
    $tickets = [];
    while ($row = mysqli_fetch_assoc($result)) {
        //fetch unread replies
        $ticketId = $row['id'];
        $repliesQuery = mysqli_query($conn, "SELECT `notification` FROM `ticket_notification` WHERE `ticket_id` = $ticketId AND `status`='unread';");
        $replies = mysqli_fetch_all($repliesQuery, MYSQLI_ASSOC);
        $row['unread_count'] = mysqli_num_rows($repliesQuery);
        $row['unread_notifications'] = $replies;
        $tickets[] = $row;
    }

    // Free resources and close the statement
    mysqli_stmt_close($stmt);

    // Return the tickets
    return $tickets;
}

//function to fetch chats for a particular ticket
function fetch_ticket_chats($ticket_id) {
    global $conn;
    // Prepare the SQL query
    $query = "SELECT tc.id,`user_type`,`response`,ta.description AS attachment,tc.created_at FROM `ticket_chat` tc LEFT JOIN `ticket_attachement` ta ON tc.id=ta.ticket_res_id WHERE `ticket_id`=? AND `response_type`=2 ORDER BY tc.`id` ASC;";
    
    // Prepare the statement
    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        error_log("Query preparation failed: " . mysqli_error($conn));
        return null; // Return null on preparation error
    }
    
    // Bind the parameter
    if (!mysqli_stmt_bind_param($stmt, 'i', $ticket_id)) {
        error_log("Parameter binding failed: " . mysqli_error($conn));
        return null; // Return null on binding error
    }
    
    // Execute the statement
    if (!mysqli_stmt_execute($stmt)) {
        error_log("Query execution failed: " . mysqli_error($conn));
        return null; // Return null on execution error
    }
    
    // Fetch the results
    $result = mysqli_stmt_get_result($stmt);
    if (!$result) {
        error_log("Fetching results failed: " . mysqli_error($conn));
        return null; // Return null if fetching results fails
    }
    
    // Store the chat-messages in an array
    $messages = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $messages[] = $row;
    }

    // Free resources and close the statement
    mysqli_stmt_close($stmt);
//echo $messages;
    // Return the tickets
    return $messages;
}

//function to mark a notification as read
function read_notif($ticketId){
    global $conn;
    $query = "UPDATE `ticket_notification` SET `status`='read' WHERE `ticket_id`=?";
    
    // Prepare the statement
    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        error_log("Query preparation failed: " . mysqli_error($conn));
        return null; // Return null on preparation error
    }
    
    // Bind the parameter
    if (!mysqli_stmt_bind_param($stmt, 'i', $ticketId)) {
        error_log("Parameter binding failed: " . mysqli_error($conn));
        return null; // Return null on binding error
    }
    
    // Execute the statement
    if (!mysqli_stmt_execute($stmt)) {
        error_log("Query execution failed: " . mysqli_error($conn));
        return null; // Return null on execution error
    }
  return 200;  
}

function closed_tickets($email) {
    global $conn;
    $query = "SELECT * FROM `tickets` WHERE `member_email` = ? AND `status` = 'closed'";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    return mysqli_fetch_all($result, MYSQLI_ASSOC) ?? []; // Fetch all rows as an associative array
}
function open_tickets($email) {
    global $conn;
    $query = "SELECT * FROM `tickets` WHERE `member_email` = ? AND `status` = 'open'";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    return mysqli_fetch_all($result, MYSQLI_ASSOC) ?? []; // Fetch all rows as an associative array
}
function all_tickets($email) {
    global $conn;
    $query = "SELECT * FROM `tickets` WHERE `member_email` = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    return mysqli_fetch_all($result, MYSQLI_ASSOC) ?? []; // Fetch all rows as an associative array
}


// Handle API action
$action = $_GET['action'];
$email = $_GET['student_id'];

switch ($action) {
    case 'closed_tickets':
        $closed_tickets = closed_tickets($email);
        $closed_tickets
            ? sendResponse(200, "success", "Tickets found", $closed_tickets)
            : sendResponse(404, "not found", "Invalid email");
        break;

    case 'open_tickets':
        $open_tickets = closed_tickets($email);
        $open_tickets
            ? sendResponse(200, "success", "Tickets found", $open_tickets)
            : sendResponse(500, "error", "Unexpected error");
        break;
    case 'all_tickets':
        $open_tickets = all_tickets($email);
        $open_tickets
            ? sendResponse(200, "success", "Tickets found", $open_tickets)
            : sendResponse(500, "error", "Unexpected error");
        break;
        case 'my_tickets':
        $my_tickets = fetch_tickets($email);

        if ($my_tickets === null) {
            // Case 1: Query failed or unexpected error
            sendResponse(500, "error", "Unexpected error occurred while retrieving tickets");
        } else {
            // Case 2: Tickets found or empty
            sendResponse(200, "success", count($my_tickets) . " tickets found", $my_tickets);
        }
        break;

    case 'chat_messages':
        validate_inputs($_GET, ['ticket_id']);
        $ticketId = $_GET['ticket_id'];
        $messages = fetch_ticket_chats($ticketId);

        if ($messages === null) {
            // Case 1: Query failed or unexpected error
            sendResponse(500, "error", "Unexpected error occurred while retrieving messages");
        } else {
            // Case 2: Messages found or empty
            sendResponse(200, "success", count($messages) . " messages found", $messages);
        }
        break;

    case 'read_notif':
        validate_inputs($_GET, ['ticket_id']);
        $ticketId = $_GET['ticket_id'];
        $messages = read_notif($ticketId);

        if ($messages === null) {
            // Case 1: Query failed or unexpected error
            sendResponse(500, "error", "Unexpected error occurred while marking notifications as read");
        } else {
            // Case 2: Notifications successfully marked as read
            sendResponse(200, "success", "Notifications marked as read", $messages);
        }
        break;

    default:
        sendResponse(400, "error", "Invalid action");
}
?>
