<?php
/**
 * SmartFlowFX - update-deposit-status.php
 * Approve or Reject a deposit from admin panel
 */

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once '../config/db.php';
mysqli_query($conn, "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["status" => "error", "message" => "Invalid request method"]);
    exit;
}

// Accept both JSON body and form POST
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) $input = $_POST;

$id        = intval($input['id']        ?? 0);
$newStatus = trim($input['status']      ?? '');
$txHash    = trim($input['tx_hash']     ?? '');
$adminNote = trim($input['admin_note']  ?? '');

// Validate
if ($id <= 0) {
    echo json_encode(["status" => "error", "message" => "Invalid deposit ID"]);
    exit;
}

$allowed = ['success', 'rejected', 'pending'];
if (!in_array($newStatus, $allowed)) {
    echo json_encode(["status" => "error", "message" => "Invalid status value"]);
    exit;
}

// Check deposit exists
$dep = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT id, wallet, amount, status FROM deposits WHERE id = $id LIMIT 1"
));
if (!$dep) {
    echo json_encode(["status" => "error", "message" => "Deposit not found"]);
    exit;
}

// Build update
$now        = date('Y-m-d H:i:s');
$safeNote   = mysqli_real_escape_string($conn, $adminNote);
$safeTxHash = mysqli_real_escape_string($conn, $txHash);

$setParts = ["status = '$newStatus'", "approved_at = '$now'"];
if ($safeTxHash)  $setParts[] = "tx_hash = '$safeTxHash'";
if ($safeNote)    $setParts[] = "admin_note = '$safeNote'";
$setClause = implode(', ', $setParts);

$upd = mysqli_query($conn, "UPDATE deposits SET $setClause WHERE id = $id");

if (!$upd) {
    echo json_encode(["status" => "error", "message" => "DB error: " . mysqli_error($conn)]);
    exit;
}

// If approving — also update user status to 'active' in users table
if ($newStatus === 'success') {
    $wallet = mysqli_real_escape_string($conn, $dep['wallet']);
    mysqli_query($conn, "UPDATE users SET status = 'active' WHERE wallet = '$wallet' AND status != 'blocked'");
}

echo json_encode([
    "status"     => "success",
    "message"    => $newStatus === 'success' ? "Deposit approved successfully" : "Deposit rejected",
    "deposit_id" => $id,
    "new_status" => $newStatus,
]);
?>