<?php
// Backend API
header('Content-Type: application/json');
require 'config.php';

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die(json_encode(['error' => 'Database connection failed']));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $ownCode = $conn->real_escape_string($_POST['ownCode'] ?? '');

    // Get user data
    $userQuery = $conn->prepare("SELECT * FROM shonu_subjects WHERE owncode = ?");
    $userQuery->bind_param('s', $ownCode);
    $userQuery->execute();
    $userResult = $userQuery->get_result();

    if ($userResult->num_rows === 0) {
        echo json_encode(['error' => 'User not found']);
        exit;
    }

    $user = $userResult->fetch_assoc();
    $userId = $user['id'];
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    // Get commission data
    $commissionQuery = $conn->prepare("
        SELECT SUM(ayoga) as total_commission, COUNT(*) as bet_count, SUM(ketebida) as total_bet 
        FROM vyavahara 
        WHERE balakedara = ? AND DATE(tiarikala) = ?
    ");
    $commissionQuery->bind_param('ss', $userId, $yesterday);
    $commissionQuery->execute();
    $commissionResult = $commissionQuery->get_result()->fetch_assoc();

    // Get deposit data
    $depositQuery = $conn->prepare("
        SELECT 
            COUNT(*) as total_deposits,
            SUM(motta) as total_deposit_amount,
            SUM(CASE WHEN first_deposit = 1 THEN 1 ELSE 0 END) as first_deposit_count,
            SUM(CASE WHEN first_deposit = 1 THEN motta ELSE 0 END) as first_deposit_total
        FROM thevani 
        WHERE balakedara = ? AND DATE(dinankavannuracisi) = ?
    ");
    $depositQuery->bind_param('ss', $userId, $yesterday);
    $depositQuery->execute();
    $depositResult = $depositQuery->get_result()->fetch_assoc();

    echo json_encode([
        'user' => $user,
        'commission' => $commissionResult,
        'deposit' => $depositResult
    ]);
    exit;
}
?>
