<?php
header('Content-Type: application/json');

// DB credentials
$host = 'localhost';
$user = 'staraviat_main';
$pass = 'staraviat_main';
$dbname = 'staraviat_main';

// Read JSON input
$input = json_decode(file_get_contents('php://input'), true);
$userid = intval($input['userid'] ?? 0);

// Connect to DB
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

// Get successful credit transactions
$sqlCredit = "SELECT amount FROM transactions WHERE userid = ? AND type = 'credit' AND status = 1";
$stmtCredit = $conn->prepare($sqlCredit);
$stmtCredit->bind_param("i", $userid);
$stmtCredit->execute();
$resultCredit = $stmtCredit->get_result();

$creditAmounts = [];
while ($row = $resultCredit->fetch_assoc()) {
    $creditAmounts[] = floatval($row['amount']);
}
$stmtCredit->close();

// Get successful withdraw transactions
$sqlWithdraw = "SELECT COUNT(*) as withdraw_count FROM transactions WHERE userid = ? AND type = 'debit' AND status = 0";
$stmtWithdraw = $conn->prepare($sqlWithdraw);
$stmtWithdraw->bind_param("i", $userid);
$stmtWithdraw->execute();
$withdrawResult = $stmtWithdraw->get_result();
$withdrawCount = $withdrawResult->fetch_assoc()['withdraw_count'];
$stmtWithdraw->close();

$conn->close();

// Logic
$depositCount = count($creditAmounts);
$has1799 = in_array(1799, $creditAmounts);

$response = ['show' => false, 'modal' => 0];

if ($depositCount === 0) {
    $response = ['show' => true, 'modal' => 1];
} elseif ($depositCount === 1) {
    $response = ['show' => false, 'modal' => 2];
} elseif ($depositCount >= 3 && $has1799 && $withdrawCount >= 1) {
    $response = ['show' => false, 'modal' => 4];
} elseif ($depositCount > 1 && $has1799 && $withdrawCount >= 1) {
    $response = ['show' => false, 'modal' => 3];
} elseif ($depositCount >1 && $has1799) {
    $response = ['show' => true, 'modal' => 1];
} 

echo json_encode($response);
