<?php
session_start();
header('Content-Type: application/json');
require_once 'config.php';

global $pdo;

$pdo->exec("CREATE TABLE IF NOT EXISTS support_tickets (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    problem_type VARCHAR(50) NOT NULL,
    status ENUM('open','closed') DEFAULT 'open',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS support_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ticket_id INT NOT NULL,
    is_admin TINYINT(1) DEFAULT 0,
    message TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'list') {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'tickets' => [], 'messages' => []]);
        exit;
    }
    $uid = (int)$_SESSION['user_id'];
    $tickets = $pdo->prepare("SELECT id, problem_type, status, created_at FROM support_tickets WHERE user_id = ? ORDER BY id DESC");
    $tickets->execute([$uid]);
    echo json_encode(['success' => true, 'tickets' => $tickets->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

if ($action === 'messages') {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'messages' => []]);
        exit;
    }
    $tid = (int)($_GET['ticket_id'] ?? 0);
    $t = $pdo->prepare("SELECT id FROM support_tickets WHERE id = ? AND user_id = ?");
    $t->execute([$tid, $_SESSION['user_id']]);
    if (!$t->fetch()) {
        echo json_encode(['success' => false, 'messages' => []]);
        exit;
    }
    $msgs = $pdo->prepare("SELECT id, is_admin, message, created_at FROM support_messages WHERE ticket_id = ? ORDER BY id ASC");
    $msgs->execute([$tid]);
    echo json_encode(['success' => true, 'messages' => $msgs->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'create') {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required']);
        exit;
    }
    $type = trim($_POST['problem_type'] ?? '');
    $msg = trim($_POST['message'] ?? '');
    $types = ['withdraw_problem', 'deposit_problem', 'bonus_problem', 'bug_problem', 'advance_option', 'contact_agent'];
    if (!in_array($type, $types) || $msg === '') {
        echo json_encode(['success' => false, 'message' => 'Invalid type or empty message']);
        exit;
    }
    $pdo->prepare("INSERT INTO support_tickets (user_id, problem_type, status) VALUES (?, ?, 'open')")->execute([$_SESSION['user_id'], $type]);
    $ticketId = $pdo->lastInsertId();
    $pdo->prepare("INSERT INTO support_messages (ticket_id, is_admin, message) VALUES (?, 0, ?)")->execute([$ticketId, $msg]);
    echo json_encode(['success' => true, 'ticket_id' => (int)$ticketId]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'reply') {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false]);
        exit;
    }
    $tid = (int)($_POST['ticket_id'] ?? 0);
    $msg = trim($_POST['message'] ?? '');
    if ($msg === '') {
        echo json_encode(['success' => false]);
        exit;
    }
    $t = $pdo->prepare("SELECT id FROM support_tickets WHERE id = ? AND user_id = ? AND status = 'open'");
    $t->execute([$tid, $_SESSION['user_id']]);
    if (!$t->fetch()) {
        echo json_encode(['success' => false]);
        exit;
    }
    $pdo->prepare("INSERT INTO support_messages (ticket_id, is_admin, message) VALUES (?, 0, ?)")->execute([$tid, $msg]);
    echo json_encode(['success' => true]);
    exit;
}

echo json_encode(['success' => false]);
