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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: create_ticket.php');
    exit();
}

// Get user ID
$user_id = $_SESSION['user_id'];

// Collect form data
$reference_number = $_POST['reference_number'] ?? '';
$subject = $_POST['subject'] ?? '';
$category = $_POST['category'] ?? '';
$priority = $_POST['priority'] ?? 'medium';
$message = $_POST['message'] ?? '';

// Validate required fields
if (empty($reference_number) || empty($subject) || empty($category) || empty($message)) {
    $_SESSION['error_message'] = "All required fields must be filled.";
    header('Location: create_ticket.php');
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Create the ticket
    $sql = "INSERT INTO support_tickets (
                reference_number, user_id, subject, priority, category, status
            ) VALUES (?, ?, ?, ?, ?, 'open')";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Error preparing statement: " . $conn->error);
    }
    
    $stmt->bind_param("sisss", $reference_number, $user_id, $subject, $priority, $category);
    
    if (!$stmt->execute()) {
        throw new Exception("Error creating ticket: " . $stmt->error);
    }
    
    $ticket_id = $conn->insert_id;
    
    // Add the initial message
    $sql = "INSERT INTO ticket_messages (
                ticket_id, user_id, message
            ) VALUES (?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Error preparing statement: " . $conn->error);
    }
    
    $stmt->bind_param("iis", $ticket_id, $user_id, $message);
    
    if (!$stmt->execute()) {
        throw new Exception("Error adding message: " . $stmt->error);
    }
    
    $message_id = $conn->insert_id;
    
    // Handle file uploads
    if (!empty($_FILES['file']) && is_array($_FILES['file']['name'])) {
        $upload_dir = 'uploads/tickets/';
        
        // Create directory if it doesn't exist
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        // Process each file
        for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
            if ($_FILES['file']['error'][$i] === UPLOAD_ERR_OK) {
                $tmp_name = $_FILES['file']['tmp_name'][$i];
                $name = basename($_FILES['file']['name'][$i]);
                $file_type = $_FILES['file']['type'][$i];
                $file_size = $_FILES['file']['size'][$i];
                
                // Generate unique filename
                $new_filename = uniqid() . '_' . $name;
                $upload_path = $upload_dir . $new_filename;
                
                if (move_uploaded_file($tmp_name, $upload_path)) {
                    // Save file info to database
                    $sql = "INSERT INTO ticket_attachments (
                                message_id, file_name, file_path, file_type, file_size
                            ) VALUES (?, ?, ?, ?, ?)";
                    
                    $stmt = $conn->prepare($sql);
                    if (!$stmt) {
                        throw new Exception("Error preparing statement: " . $conn->error);
                    }
                    
                    $stmt->bind_param("isssi", $message_id, $name, $upload_path, $file_type, $file_size);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("Error saving attachment: " . $stmt->error);
                    }
                } else {
                    throw new Exception("Error uploading file: " . $name);
                }
            }
        }
    }
    
    // Create notification for admin/support staff
    // This is simplified - you might want to improve notification handling
    //$notif_message = "New support ticket ({$reference_number}) has been created.";
    //$sql_notif = "INSERT INTO notifications (
    //                file_id, notif_message, created_at
    //              ) VALUES (1, ?, NOW())";  // Assuming user_id 1 is admin
    
    //$notif_stmt = $conn->prepare($sql_notif);
    //if ($notif_stmt) {
    //    $notif_stmt->bind_param("s", $notif_message);
    //    $notif_stmt->execute();
    //}
    
    // Commit transaction
    $conn->commit();
    
    // Success message and redirect
    $_SESSION['success_message'] = "Your ticket has been submitted successfully. Reference Number: {$reference_number}";
    header('Location: my_tickets.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: create_ticket.php');
    exit();
}
?>