<?php
header('Content-Type: application/json');
// Enable error reporting for debugging
error_reporting(E_ALL | E_WARNING | E_NOTICE);

// Database connection
require "../../../../database/conn.php";
global $conn;

$response = ["success" => false, "message" => "An error occurred."];

try {
    // Validate the request method
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Invalid request method. Please use POST.");
    }

    // Validate required parameters
    if (!isset($_GET['student_id']) || !isset($_REQUEST['category'], $_REQUEST['issue'], $_REQUEST['phone'])) {
        throw new Exception("Missing required parameters: student_id, category, issue, or phone.");
    }

    // Sanitize and validate inputs
    $email = filter_var($_GET['student_id'], FILTER_VALIDATE_EMAIL);
    $category = htmlspecialchars(trim($_REQUEST['category']));
    $issue = htmlspecialchars(trim($_REQUEST['issue']));
    $phone = htmlspecialchars(trim($_REQUEST['phone']));

    // Prepare and execute user lookup with prepared statement
    $stmt = $conn->prepare("SELECT * FROM members WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception("User not found.");
    }

    $user = $result->fetch_assoc();

    // Set timezone and get current date
    date_default_timezone_set('Africa/Nairobi');
    $ticket_date = date("Y-m-d H:i");

    // Parse names
    $names = $user['fullnames'];
    $name_parts = explode(" ", $names);
    $lastname = array_pop($name_parts);
    $firstname = implode(" ", $name_parts);

    // Generate random ticket identifier
    $rand = rand(11111, 99999);

    // File handling
    $newfilename = null;
    if (isset($_FILES['file']) && !empty($_FILES['file']['name'])) {
        $file_ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];

        if (!in_array($file_ext, $allowed_extensions)) {
            throw new Exception("Invalid file type. Allowed types: " . implode(', ', $allowed_extensions));
        }

        $newfilename = round(microtime(true)) . $rand . 'ticket.' . $file_ext;
        $uploadPath = "imgs/tickets/" . $newfilename;

        if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
            throw new Exception("Failed to upload the file.");
        }

        $newfilename = "./imgs/tickets/" . $newfilename;
    }

    // Prepare and execute ticket insertion with prepared statement
    $stmt = $conn->prepare("INSERT INTO tickets (fullnames, member_email, category, issue, phone, ticket_date, status" . 
        ($newfilename ? ", img" : "") . 
        ") VALUES (?, ?, ?, ?, ?, ?, 'new'" . 
        ($newfilename ? ", ?" : "") . 
        ")");

    // Bind parameters dynamically based on file upload
    if ($newfilename) {
        $stmt->bind_param("sssssss", $names, $email, $category, $issue, $phone, $ticket_date, $newfilename);
    } else {
        $stmt->bind_param("ssssss", $names, $email, $category, $issue, $phone, $ticket_date);
    }

    if (!$stmt->execute()) {
        throw new Exception("Failed to submit the ticket.");
    }

    $response["success"] = true;
    $response["message"] = "Success. Your ticket has been received. We will update you once the issue is resolved.";

} catch (Exception $e) {
    $response["message"] = $e->getMessage();
} finally {
    // Close any open database connections
    if (isset($stmt)) $stmt->close();
    if (isset($conn)) $conn->close();
}

// Return the response as JSON
echo json_encode($response);
?>