<?php
// Endpoint: crear ticket de soporte
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

header('Content-Type: application/json; charset=utf-8');

function error_response($msg, $code = 400) {
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

if (!isset($_SESSION['client_id'])) {
    error_response('No autenticado', 401);
}
$client_id = (int)$_SESSION['client_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_response('Método no permitido', 405);
}

$subject = trim($_POST['subject'] ?? '');
$message = trim($_POST['message'] ?? '');
$priority = trim($_POST['priority'] ?? 'medium');

if ($subject === '' || $message === '') {
    error_response('Asunto y mensaje son obligatorios');
}

if (!in_array($priority, ['low','medium','high'], true)) { $priority = 'medium'; }

$db = Database::getInstance();
$pdo = $db->getConnection();

$stmt = $pdo->prepare("INSERT INTO support_tickets (client_id, subject, message, status, priority, created_at) VALUES (?, ?, ?, 'open', ?, NOW())");
$stmt->execute([$client_id, $subject, $message, $priority]);

echo json_encode([
    'success' => true,
    'ticket_id' => $pdo->lastInsertId(),
    'status' => 'open'
]);
?>