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

// Get all data
$from        = $_GET['from'] ?? '';
$body        = $_GET['body'] ?? '';
$raw_amount  = $_GET['amount'] ?? ''; 
$trype       = $_GET['trype'] ?? '';
$trnxid      = $_GET['trnxid'] ?? '';
$key         = $_GET['key'] ?? '';
$sender      = $_GET['sender'] ?? '';
$deviceid    = $_GET['deviceid'] ?? '';
$Gateway     = $_GET['Gateway'] ?? '';
$Method      = $_GET['Method'] ?? '';
$status      = $_GET['status'] ?? '';
$acount_trype = 'free';

// ⭐ Amount কে Floating Point সংখ্যায় রূপান্তর (Decimal কলামের জন্য)
$amount = (float) $raw_amount; 

// Required check
if (empty($from) || empty($trnxid) || empty($key) || empty($deviceid)) {
    echo json_encode(["status" => "error", "message" => "Missing required fields"]);
    exit;
}

// Step 1: Check trnxid already exists
$checkTrnx = $conn->prepare("SELECT * FROM ShuvoPays WHERE trnxid = ?");
$checkTrnx->bind_param("s", $trnxid);
$checkTrnx->execute();
$resultTrnx = $checkTrnx->get_result();

if ($resultTrnx->num_rows > 0) {
    echo json_encode(["status" => "error", "message" => "This Message Already Exists"]);
    exit;
}

// Step 2: DeviceID logic based on key
$isPro = (stripos($key, 'pro') !== false);

if (!$isPro) {
    $checkKey = $conn->prepare("SELECT deviceid FROM ShuvoPays WHERE `key` = ? LIMIT 1");
    $checkKey->bind_param("s", $key);
    $checkKey->execute();
    $resKey = $checkKey->get_result();

    if ($resKey->num_rows > 0) {
        $row = $resKey->fetch_assoc();
        $firstDevice = $row['deviceid'];

        if ($deviceid !== $firstDevice) {
            echo json_encode(["status" => "error", "message" => "Device not allowed for this key"]);
            exit;
        }
    }
}

// Step 3: Check duplicate message (exact same)
$checkDuplicate = $conn->prepare("SELECT * FROM ShuvoPays WHERE `from`=? AND body=? AND amount=? AND trype=? AND `key`=? AND sender=? AND deviceid=? AND acount_trype=? AND Gateway=? AND Method=? AND status=?");
$checkDuplicate->bind_param("ssdssssssss", $from, $body, $amount, $trype, $key, $sender, $deviceid, $acount_trype, $Gateway, $Method, $status);
$checkDuplicate->execute();
$resultDup = $checkDuplicate->get_result();

if ($resultDup->num_rows > 0) {
    echo json_encode(["status" => "error", "message" => "Duplicate Data"]);
    exit;
}

// ✅ Step 4: Insert data with created_at (PHP current time)
$created_at = date("Y-m-d h:i A"); // 12-hour format, যেমন আগের POST কোডে ছিল

try {
    $insert = $conn->prepare("INSERT INTO ShuvoPays (`from`, body, amount, trype, trnxid, `key`, sender, deviceid, acount_trype, Gateway, Method, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $insert->bind_param("ssdssssssssss", $from, $body, $amount, $trype, $trnxid, $key, $sender, $deviceid, $acount_trype, $Gateway, $Method, $status, $created_at);

    if ($insert->execute()) {
        echo json_encode(["status" => "success", "message" => "Data Inserted Successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Insert Failed: MySQL Error - " . $conn->error]);
    }
} catch (ArgumentCountError $e) {
    echo json_encode(["status" => "error", "message" => "Insert Failed: Fatal Error in bind_param count. Details: " . $e->getMessage()]);
} catch (Throwable $e) {
    echo json_encode(["status" => "error", "message" => "Insert Failed: General Error - " . $e->getMessage()]);
}

$conn->close();
?>