<?php
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';

// INPUT
$wallet = trim($_POST['wallet'] ?? '');
$amount = floatval($_POST['amount'] ?? 0);
$txHash = trim($_POST['tx_hash'] ?? '');

if (empty($wallet)) {
    $raw    = json_decode(file_get_contents('php://input'), true);
    $wallet = trim($raw['wallet'] ?? '');
    $amount = floatval($raw['amount'] ?? 0);
    $txHash = trim($raw['tx_hash'] ?? '');
}

// VALIDATION — ⚠️ Testing ke baad MIN = 60 karo
$MIN = 1; $MAX = 1000;
if (empty($wallet) || $amount <= 0)          { echo json_encode(["status"=>"error","message"=>"Invalid data"]); exit; }
if ($amount < $MIN || $amount > $MAX)        { echo json_encode(["status"=>"error","message"=>"Amount \$$MIN–\$$MAX hona chahiye"]); exit; }

// DUPLICATE CHECK
if (!empty($txHash)) {
    $s = $conn->prepare("SELECT id FROM deposits WHERE tx_hash = ?");
    $s->bind_param("s", $txHash); $s->execute();
    if ($s->get_result()->fetch_assoc()) {
        echo json_encode(["status"=>"success","message"=>"Already recorded","data"=>["total_credited"=>$amount]]);
        exit;
    }
    $s->close();
}

// FIND USER
$s = $conn->prepare("SELECT id, account_id, referral_id FROM users WHERE LOWER(wallet) = LOWER(?)");
$s->bind_param("s", $wallet); $s->execute();
$user = $s->get_result()->fetch_assoc(); $s->close();

if (!$user) { echo json_encode(["status"=>"error","message"=>"User not found: $wallet"]); exit; }

$referral_id = $user['referral_id'] ?? '';
$now         = date('Y-m-d H:i:s');

// Package type
function getPackageType($a) {
    if ($a <= 1)   return 'test';
    if ($a <= 60)  return 'starter';
    if ($a <= 250) return 'basic';
    if ($a <= 500) return 'standard';
    return 'premium';
}
$packageType  = getPackageType($amount);
$daily_rate   = 0.25;
$monthly_rate = 7.5;
$yearly_cap   = 200;
$network      = 'BSC-BEP20';
$notes        = 'Auto deposit via Web3';
$screenshot   = '';

$conn->begin_transaction();
try {
    // 1. INSERT into deposits
    // Columns: wallet, amount, package_type, network, tx_hash, notes, screenshot,
    //          monthly_rate, daily_rate, yearly_cap, status,
    //          admin_note, approved_by, approved_at, created_at
    $s = $conn->prepare(
        "INSERT INTO deposits
            (wallet, amount, package_type, network, tx_hash, notes, screenshot,
             monthly_rate, daily_rate, yearly_cap,
             status, admin_note, approved_by, approved_at, created_at)
         VALUES (?,?,?,?,?,?,?, ?,?,?, 'approved','','',?,?)"
    );
    $s->bind_param("sdsssss" . "ddd" . "ss",
        $wallet, $amount, $packageType, $network, $txHash, $notes, $screenshot,
        $monthly_rate, $daily_rate, $yearly_cap,
        $now, $now
    );
    $s->execute();
    $depositId = $s->insert_id;
    $s->close();

    // 2. Update user
    $s = $conn->prepare(
        "UPDATE users SET
            balance      = balance + ?,
            status       = 'active',
            is_activated = 1,
            joining_date = IF(joining_date IS NULL OR joining_date='0000-00-00', ?, joining_date)
         WHERE LOWER(wallet) = LOWER(?)"
    );
    $s->bind_param("dss", $amount, $now, $wallet); $s->execute(); $s->close();

    // 3. 10% direct income to sponsor
    $directIncome = 0;
    if (!empty($referral_id)) {
        $s = $conn->prepare("SELECT wallet FROM users WHERE account_id = ?");
        $s->bind_param("s", $referral_id); $s->execute();
        $sponsor = $s->get_result()->fetch_assoc(); $s->close();
        if ($sponsor) {
            $directIncome  = round($amount * 0.10, 4);
            $sw = $sponsor['wallet'];
            $s  = $conn->prepare("UPDATE users SET direct_profit=direct_profit+?, balance=balance+?, direct_business=direct_business+? WHERE wallet=?");
            $s->bind_param("ddds", $directIncome, $directIncome, $amount, $sw);
            $s->execute(); $s->close();
        }
    }

    $conn->commit();
    echo json_encode([
        "status"  => "success",
        "message" => "Deposit successful!",
        "data"    => ["deposit_id"=>$depositId,"amount"=>$amount,"total_credited"=>$amount,"package"=>$packageType,"direct_income"=>$directIncome]
    ]);

} catch(Exception $e) {
    $conn->rollback();
    echo json_encode(["status"=>"error","message"=>"DB error: ".$e->getMessage()]);
}
?>