<?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']]);
    }
});

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

$id     = intval($_POST['id']     ?? 0);
$reply  = trim($_POST['reply']    ?? '');
$status = trim($_POST['status']   ?? 'resolved');

if (!$id)    jsonOut('error', 'Ticket ID missing.');
if (!$reply) jsonOut('error', 'Reply text is required.');

$allowed = ['open', 'pending', 'resolved', 'closed'];
if (!in_array($status, $allowed)) $status = 'resolved';

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

$stmt = $conn->prepare(
    "UPDATE support_tickets SET admin_reply = ?, status = ?, updated_at = NOW() WHERE id = ?"
);
if (!$stmt) jsonOut('error', 'Prepare failed: ' . $conn->error);

$stmt->bind_param('ssi', $reply, $status, $id);

if ($stmt->execute() && $stmt->affected_rows > 0) {
    jsonOut('success', 'Reply sent successfully.');
} else {
    jsonOut('error', 'Update failed or ticket not found. ' . $stmt->error);
}

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