<?php
header('Content-Type: application/json');
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$user_id = $auth->getCurrentUserId();
$functions = new Functions();

// Get POST data
$subject = isset($_POST['subject']) ? $functions->sanitize($_POST['subject']) : '';
$message = isset($_POST['message']) ? $functions->sanitize($_POST['message']) : '';
$category = isset($_POST['category']) ? $functions->sanitize($_POST['category']) : 'general';
$priority = isset($_POST['priority']) ? $functions->sanitize($_POST['priority']) : 'medium';

// Validate input
if (empty($subject) || empty($message)) {
    echo json_encode(['success' => false, 'message' => 'Subject and message are required']);
    exit();
}

// Generate unique ticket ID
$ticket_id = 'TICKET-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 6));

try {
    // Create support ticket
    $stmt = $functions->db->prepare("
        INSERT INTO support_tickets (user_id, ticket_id, subject, message, category, priority, status)
        VALUES (?, ?, ?, ?, ?, ?, 'open')
    ");

    $result = $stmt->execute([
        $user_id,
        $ticket_id,
        $subject,
        $message,
        $category,
        $priority
    ]);

    if ($result) {
        $ticket_db_id = $functions->db->lastInsertId();

        // Log activity
        $functions->logActivity($user_id, 'ticket_created', 'Created support ticket ' . $ticket_id);

        echo json_encode([
            'success' => true,
            'message' => 'Support ticket created successfully',
            'data' => [
                'ticket_id' => $ticket_id,
                'db_id' => $ticket_db_id,
                'subject' => $subject,
                'category' => $category,
                'priority' => $priority,
                'status' => 'open',
                'created_at' => date('Y-m-d H:i:s')
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to create support ticket']);
    }

} catch (Exception $e) {
    error_log("Ticket creation error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Failed to create support ticket. Please try again.']);
}
?>
