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

// ── DB config ──────────────────────────────────────────────
define('DB_HOST', 'localhost');
define('DB_USER', 'redhash_leoexx');        // ← change
define('DB_PASS', '$?P;XUSaG6u%m+3h');            // ← change
define('DB_NAME', 'redhash_leoexx');   // ← change

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonOut('error', 'Method not allowed.');
}

$wallet   = trim($_POST['wallet']   ?? '');
$name     = trim($_POST['name']     ?? '');
$category = trim($_POST['category'] ?? '');
$subject  = trim($_POST['subject']  ?? '');
$message  = trim($_POST['message']  ?? '');

// ── Validation ─────────────────────────────────────────────
if (!$wallet)              jsonOut('error', 'Wallet address missing.');
if (!$name)                jsonOut('error', 'Name is required.');
if (strlen($message) < 15) jsonOut('error', 'Message too short (min 15 chars).');
if (!$subject)             jsonOut('error', 'Subject is required.');

$allowed_cats = ['deposit', 'withdrawal', 'roi', 'account', 'other'];
if (!in_array($category, $allowed_cats)) $category = 'other';

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

// ── Insert ─────────────────────────────────────────────────
$stmt = $conn->prepare(
    "INSERT INTO support_tickets (wallet, name, category, subject, message, status, created_at)
     VALUES (?, ?, ?, ?, ?, 'open', NOW())"
);
$stmt->bind_param('sssss', $wallet, $name, $category, $subject, $message);

if ($stmt->execute()) {
    $ticketId = $stmt->insert_id;
    jsonOut('success', 'Ticket submitted successfully.', ['ticket_id' => $ticketId]);
} else {
    jsonOut('error', 'Failed to save ticket. Try again.');
}

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