<?php
// backend/api/get-tickets.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
define('DB_HOST', 'localhost');
define('DB_USER', 'redhash_leoexx');        // ← change
define('DB_PASS', '$?P;XUSaG6u%m+3h');            // ← change
define('DB_NAME', 'redhash_leoexx'); 

function jsonOut($status, $message, $extra = []) {
    echo json_encode(array_merge(['status' => $status, 'message' => $message], $extra));
    exit;
}

$wallet = trim($_GET['wallet'] ?? '');
if (!$wallet) jsonOut('error', 'Wallet address missing.', ['tickets' => []]);

// ── DB connect ─────────────────────────────────────────────
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    jsonOut('error', 'Database connection failed.', ['tickets' => []]);
}

// ── Fetch tickets ──────────────────────────────────────────
$stmt = $conn->prepare(
    "SELECT id, category, subject, status, admin_reply,
            DATE_FORMAT(created_at, '%d %b %Y') AS created_at
     FROM support_tickets
     WHERE wallet = ?
     ORDER BY created_at DESC
     LIMIT 50"
);
$stmt->bind_param('s', $wallet);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];
while ($row = $result->fetch_assoc()) {
    $tickets[] = $row;
}

echo json_encode(['status' => 'success', 'tickets' => $tickets]);

$stmt->close();
$conn->close();