<?php
header("Content-Type: application/json; charset=UTF-8");
require_once __DIR__ . "/../config.php";

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

// Debug: see exactly what PHP receives (can comment out later)
// echo json_encode(['post'=>$_POST,'files'=>$_FILES]); exit();

// Read POST fields
$wallet_name = trim($_POST['wallet_name'] ?? '');
$wallet_address = trim($_POST['wallet_address'] ?? '');
$payment_type = trim($_POST['payment_type'] ?? '');
$status = in_array($_POST['status'] ?? 'active', ['active','inactive']) ? $_POST['status'] : 'active';

// Validate required fields
if (empty($wallet_name) || empty($wallet_address)) {
    echo json_encode(["status" => "error", "message" => "wallet_name and wallet_address are required"]);
    exit();
}

// Handle QR upload
$qr_upload = null;
$uploadDir = __DIR__ . "/uploads/";
$uploadUrlPath = "uploads/";

if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

if (isset($_FILES['qr_upload']) && $_FILES['qr_upload']['error'] === UPLOAD_ERR_OK) {
    $fileTmpPath = $_FILES['qr_upload']['tmp_name'];
    $originalName = basename($_FILES['qr_upload']['name']);
    $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    $allowedExt = ['jpg','jpeg','png','gif'];

    if (!in_array($ext, $allowedExt)) {
        echo json_encode(["status" => "error", "message" => "Invalid file type. Allowed: jpg, jpeg, png, gif"]);
        exit();
    }

    $newFileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $originalName);
    $destination = $uploadDir . $newFileName;

    if (move_uploaded_file($fileTmpPath, $destination)) {
        $qr_upload = $uploadUrlPath . $newFileName;
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to upload QR image"]);
        exit();
    }
}

// Insert into database
$stmt = $conn->prepare("INSERT INTO payment_methods (wallet_name, wallet_address, payment_type, status, qr_upload) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $wallet_name, $wallet_address, $payment_type, $status, $qr_upload);

// if ($stmt->execute()) {
//     echo json_encode([
//         "status" => "success",
//         "message" => "Payment method added successfully",
//         "inserted_id" => $stmt->insert_id,
//         "qr_upload" => $qr_upload
//     ]);
// } else {
//     echo json_encode(["status" => "error", "message" => "Database insert failed: " . $stmt->error]);
// }

if ($stmt->execute()) {
    $inserted_id = $stmt->insert_id;

    // ------------------ ADD HISTORY ------------------
    $historyStmt = $conn->prepare("
        INSERT INTO payment_methods_history 
        (payment_method_id, action, wallet_name, wallet_address, payment_type, status, qr_upload, action_date) 
        VALUES (?, 'added', ?, ?, ?, ?, ?, NOW())
    ");
    $historyStmt->bind_param("isssss", $inserted_id, $wallet_name, $wallet_address, $payment_type, $status, $qr_upload);
    $historyStmt->execute();
    $historyStmt->close();
    // ------------------ END HISTORY ------------------

    echo json_encode([
        "status" => "success",
        "message" => "Payment method added successfully",
        "inserted_id" => $inserted_id,
        "qr_upload" => $qr_upload
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "Database insert failed: " . $stmt->error]);
}


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