<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// ── DB Config — EDIT THESE ─────────────────────────────────
$db_host = 'localhost';
$db_user = 'redhash_leoexx';       // ← your DB username
$db_pass = '$?P;XUSaG6u%m+3h';           // ← your DB password
$db_name = 'redhash_leoexx';  // ← your DB name

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

register_shutdown_function(function() {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR])) {
        if (!headers_sent()) header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $err['message'], 'tickets' => []]);
    }
});

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
    jsonOut('error', 'DB connection failed: ' . $conn->connect_error, ['tickets' => []]);
}
$conn->set_charset('utf8mb4');

// Auto-create table if missing
$conn->query("CREATE TABLE IF NOT EXISTS `support_tickets` (
    `id`          INT(11)      NOT NULL AUTO_INCREMENT,
    `wallet`      VARCHAR(100) NOT NULL,
    `name`        VARCHAR(100) NOT NULL DEFAULT '',
    `category`    VARCHAR(20)  NOT NULL DEFAULT 'other',
    `subject`     VARCHAR(200) NOT NULL,
    `message`     TEXT         NOT NULL,
    `status`      VARCHAR(20)  NOT NULL DEFAULT 'open',
    `admin_reply` TEXT         DEFAULT NULL,
    `created_at`  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at`  DATETIME     DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    INDEX `idx_wallet` (`wallet`),
    INDEX `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$result = $conn->query(
    "SELECT id, wallet, name, category, subject, message, status, admin_reply,
            DATE_FORMAT(created_at, '%Y-%m-%d') AS created_at
     FROM support_tickets
     ORDER BY id DESC
     LIMIT 500"
);

if (!$result) {
    jsonOut('error', 'Query failed: ' . $conn->error, ['tickets' => []]);
}

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

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