<?php
// Allow any origin (no credentials)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Max-Age: 86400');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
include "../../conn.php";
include "../../functions2.php";

date_default_timezone_set('Asia/Kolkata');
$shnunc = date("Y-m-d H:i:s");

$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $shnunc,
];

// Read input (not used heavily in this endpoint)
$shonubody = file_get_contents("php://input");
$shonupost = json_decode($shonubody, true);

// Helper to safely run a query and return result or false
function q($conn, $sql) {
    $res = $conn->query($sql);
    if ($res === false) {
        error_log("SQL Error: " . $conn->error . " | Query: " . $sql);
    }
    return $res;
}

// ensure method is not GET (logic expects POST with Authorization)
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    http_response_code(405);
    echo json_encode($res);
    exit;
}

// Validate Authorization header exists
$authHeader = isset($_SERVER['HTTP_AUTHORIZATION']) ? trim($_SERVER['HTTP_AUTHORIZATION']) : '';
if ($authHeader === '') {
    $res = ['code'=>4,'msg'=>'Missing Authorization header','msgCode'=>2,'serviceNowTime'=>$shnunc];
    http_response_code(401);
    echo json_encode($res);
    exit;
}

$bearer = explode(" ", $authHeader);
if (count($bearer) < 2) {
    $res = ['code'=>4,'msg'=>'Malformed Authorization header','msgCode'=>2,'serviceNowTime'=>$shnunc];
    http_response_code(401);
    echo json_encode($res);
    exit;
}

$author = $bearer[1];
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (!is_array($data_auth) || !isset($data_auth['status']) || $data_auth['status'] !== 'Success') {
    $res = ['code'=>4,'msg'=>'JWT validation failed','msgCode'=>2,'serviceNowTime'=>$shnunc];
    http_response_code(401);
    echo json_encode($res);
    exit;
}

// payload id
$jwt_id = isset($data_auth['payload']['id']) ? (int)$data_auth['payload']['id'] : 0;
if ($jwt_id <= 0) {
    $res = ['code'=>4,'msg'=>'Invalid JWT payload','msgCode'=>2,'serviceNowTime'=>$shnunc];
    http_response_code(401);
    echo json_encode($res);
    exit;
}

// find subject row for this token
$sesquery = "SELECT id, owncode FROM shonu_subjects WHERE akshinak = '".mysqli_real_escape_string($conn, $author)."' LIMIT 1";
$sesresult = q($conn, $sesquery);
if (!$sesresult || $sesresult->num_rows === 0) {
    $res = ['code'=>4,'msg'=>"No user found with akshinak: $author",'msgCode'=>2,'serviceNowTime'=>$shnunc];
    http_response_code(401);
    echo json_encode($res);
    exit;
}
$sesarr = $sesresult->fetch_assoc();
$referrer_id = isset($sesarr['id']) ? (int)$sesarr['id'] : 0;
$invitation_code = isset($sesarr['owncode']) ? $sesarr['owncode'] : '';

// sanity check: jwt id must match db id (you enforced earlier)
if ($jwt_id !== $referrer_id) {
    $res = [
        'code'=>9,
        'msg'=>"JWT ID ($jwt_id) does not match shonu_subjects ID ($referrer_id)",
        'msgCode'=>8,
        'serviceNowTime'=>$shnunc
    ];
    http_response_code(400);
    echo json_encode($res);
    exit;
}

// Count invitations (number of subjects having `code` equal to invitation_code)
$inv_query = "SELECT COUNT(*) AS total FROM shonu_subjects WHERE code = '".mysqli_real_escape_string($conn, $invitation_code)."'";
$inv_result = q($conn, $inv_query);
$number_of_invitations = 0;
if ($inv_result) {
    $row = $inv_result->fetch_assoc();
    $number_of_invitations = isset($row['total']) ? (int)$row['total'] : 0;
}

// Get list of referred users (ids)
$ref_query = "SELECT id FROM shonu_subjects WHERE code = '".mysqli_real_escape_string($conn, $invitation_code)."'";
$ref_result = q($conn, $ref_query);
if (!$ref_result) {
    $res = ['code'=>8,'msg'=>'Failed to fetch referral list','msgCode'=>7,'serviceNowTime'=>$shnunc];
    http_response_code(500);
    echo json_encode($res);
    exit;
}

// Prepare reward config and config_items (unchanged, only formatting)
$reward_config = [
    1 => [
        ['id' => 17, 'min_recharge' => 200, 'max_recharge' => 499.99, 'bet' => 1000, 'reward' => 60],
        ['id' => 18, 'min_recharge' => 500, 'max_recharge' => 999.99, 'bet' => 2500, 'reward' => 60],
        ['id' => 19, 'min_recharge' => 1000, 'max_recharge' => 2499.99, 'bet' => 5000, 'reward' => 170],
        ['id' => 20, 'min_recharge' => 2500, 'max_recharge' => 4999.99, 'bet' => 12500, 'reward' => 450],
        ['id' => 21, 'min_recharge' => 5000, 'max_recharge' => PHP_INT_MAX, 'bet' => 25000, 'reward' => 730]
    ],
    2 => [
        ['id' => 22, 'min_recharge' => 300, 'max_recharge' => 999.99, 'bet' => 2000, 'reward' => 80],
        ['id' => 23, 'min_recharge' => 1000, 'max_recharge' => 2499.99, 'bet' => 10000, 'reward' => 160],
        ['id' => 24, 'min_recharge' => 2500, 'max_recharge' => 4999.99, 'bet' => 25000, 'reward' => 400],
        ['id' => 25, 'min_recharge' => 5000, 'max_recharge' => 9999.99, 'bet' => 50000, 'reward' => 850],
        ['id' => 26, 'min_recharge' => 10000, 'max_recharge' => PHP_INT_MAX, 'bet' => 75000, 'reward' => 3000]
    ],
    3 => [
        ['id' => 27, 'min_recharge' => 1000, 'max_recharge' => 2499.99, 'bet' => 15000, 'reward' => 150],
        ['id' => 28, 'min_recharge' => 2500, 'max_recharge' => 4999.99, 'bet' => 37500, 'reward' => 520],
        ['id' => 29, 'min_recharge' => 5000, 'max_recharge' => 9999.99, 'bet' => 75000, 'reward' => 950],
        ['id' => 30, 'min_recharge' => 10000, 'max_recharge' => 19999.99, 'bet' => 125000, 'reward' => 3200],
        ['id' => 31, 'min_recharge' => 20000, 'max_recharge' => PHP_INT_MAX, 'bet' => 225000, 'reward' => 6800]
    ]
];

$config_items = [];
foreach ($reward_config as $type => $levels) {
    foreach ($levels as $level) {
        $config_items[] = [
            'id' => $level['id'],
            'type' => $type,
            'rechargeAmount' => number_format($level['min_recharge'], 2, '.', ''),
            'betAmount' => number_format($level['bet'], 2, '.', ''),
            'rewardAmount' => number_format($level['reward'], 2, '.', ''),
            'createTime' => "2025-03-21 13:37:52",
            'updateTime' => "2025-03-21 13:37:52",
            'days' => 6
        ];
    }
}

// Begin the transaction
$conn->begin_transaction();
try {
    // Temporarily disable FK checks (as original)
    q($conn, "SET FOREIGN_KEY_CHECKS = 0");

    $six_days_ago = date("Y-m-d H:i:s", strtotime("-6 days"));

    $effective_users = [];
    $total_reward = 0.0;

    // iterate referred users
    while ($ref_row = $ref_result->fetch_assoc()) {
        $referred_id = isset($ref_row['id']) ? (int)$ref_row['id'] : 0;
        if ($referred_id <= 0) continue;

        // ensure referred user exists (double-check)
        $check_ref_query = "SELECT id FROM shonu_subjects WHERE id = '$referred_id' LIMIT 1";
        $check_ref_result = q($conn, $check_ref_query);
        if (!$check_ref_result || $check_ref_result->num_rows === 0) {
            error_log("Referred ID $referred_id not found in shonu_subjects - skipping");
            continue;
        }

        // fetch up to 3 deposits within last 6 days
        $dep_query = "SELECT motta, dinankavannuracisi FROM thevani 
                      WHERE balakedara = '$referred_id' 
                        AND sthiti = '1' 
                        AND dinankavannuracisi >= '$six_days_ago'
                      ORDER BY dinankavannuracisi ASC 
                      LIMIT 3";
        $dep_result = q($conn, $dep_query);
        $deposits = [];
        if ($dep_result) {
            while ($dep_row = $dep_result->fetch_assoc()) {
                $deposits[] = [
                    'amount' => (float)$dep_row['motta'],
                    'timestamp' => $dep_row['dinankavannuracisi']
                ];
            }
        }

        error_log("Deposits for user $referred_id: " . json_encode($deposits));

        // Sum bets across several tables
        $bet_tables = [
            'bajikattuttate', 'bajikattuttate_drei', 'bajikattuttate_funf', 'bajikattuttate_zehn',
            'bajikattuttate_kemuru', 'bajikattuttate_kemuru_drei', 'bajikattuttate_kemuru_funf',
            'bajikattuttate_kemuru_zehn', 'bajikattuttate_aidudi', 'bajikattuttate_aidudi_drei',
            'bajikattuttate_aidudi_funf', 'bajikattuttate_aidudi_zehn'
        ];
        $total_bet = 0.0;
        foreach ($bet_tables as $table) {
            // safe table name usage - no user input in table variable
            $bet_query = "SELECT SUM(ketebida) as total FROM `$table` 
                          WHERE byabaharkarta = '$referred_id' 
                          AND tiarikala >= '$six_days_ago'";
            $bet_result = q($conn, $bet_query);
            if ($bet_result) {
                $sumRow = $bet_result->fetch_assoc();
                $total_bet += (float)($sumRow['total'] ?? 0);
            }
        }
        error_log("Total bet for user $referred_id: $total_bet");

        $user_has_reward = false;

        // for each deposit (max 3)
        foreach ($deposits as $i => $deposit) {
            $deposit_amount = $deposit['amount'];
            $deposit_type = $i + 1;
            $levels = $reward_config[$deposit_type] ?? [];

            // check if reward already exists in partner_rewards table (YOUR TABLE STRUCTURE)
            $reward_check = "SELECT id FROM partner_rewards 
                             WHERE user_id = '$referrer_id' 
                               AND invitation_code = '".mysqli_real_escape_string($conn, $invitation_code)."'
                               AND recharge_amount = '$deposit_amount'
                             LIMIT 1";
            $reward_result = q($conn, $reward_check);
            if ($reward_result && $reward_result->num_rows > 0) {
                error_log("Reward already exists for user $referred_id, deposit $deposit_amount");
                $user_has_reward = true;
                continue;
            }

            $reward_amount = 0.0;
            $reward_level = 0;
            $required_bet = 0;

            foreach ($levels as $level) {
                if ($deposit_amount >= $level['min_recharge'] && $deposit_amount <= $level['max_recharge']) {
                    $required_bet = $level['bet'];
                    if ($total_bet >= $required_bet) {
                        $reward_amount = $level['reward'];
                        $reward_level = $level['id'];
                        $total_reward += $reward_amount;
                        $user_has_reward = true;
                    }
                    break;
                }
            }

            if ($reward_amount > 0) {
                error_log("Reward for user $referred_id, deposit $deposit_amount: $reward_amount (deposit: $deposit_amount, turnover: $total_bet, required: $required_bet)");

                // Insert reward into YOUR partner_rewards table structure
                $insert_query = "INSERT INTO partner_rewards 
                                 (user_id, invitation_code, recharge_amount, bet_amount, reward_amount, last_updated) 
                                 VALUES 
                                 ('".$referrer_id."', '".mysqli_real_escape_string($conn, $invitation_code)."', 
                                  '".$deposit_amount."', '".$total_bet."', '".$reward_amount."', '".$shnunc."')";
                $insRes = q($conn, $insert_query);
                if ($insRes === false) {
                    throw new Exception("Insert failed for partner_rewards: " . $conn->error);
                }

                // Update or insert shonu_kaichila
                $check_kaichila = "SELECT kramasankhye, motta FROM shonu_kaichila 
                                   WHERE balakedara = '$referrer_id' 
                                   ORDER BY dinankavannuracisi DESC 
                                   LIMIT 1";
                $kaichila_result = q($conn, $check_kaichila);
                if ($kaichila_result && $kaichila_result->num_rows > 0) {
                    $row = $kaichila_result->fetch_assoc();
                    $existing_motta = (float)$row['motta'];
                    $new_motta = $existing_motta + $reward_amount;
                    $kramasankhye = $row['kramasankhye'];
                    $kaichila_query = "UPDATE shonu_kaichila 
                                       SET motta = '".($new_motta)."', dinankavannuracisi = '".$shnunc."' 
                                       WHERE kramasankhye = '".mysqli_real_escape_string($conn, $kramasankhye)."'";
                    $upRes = q($conn, $kaichila_query);
                    if ($upRes === false) {
                        throw new Exception("Update failed for shonu_kaichila: " . $conn->error);
                    }
                    error_log("Updated shonu_kaichila for referrer $referrer_id: motta = $new_motta");
                } else {
                    $kaichila_query = "INSERT INTO shonu_kaichila (balakedara, motta, rebet, spin, bonus, dinankavannuracisi) 
                                       VALUES ('".$referrer_id."', '".$reward_amount."', 0, 0, 0, '".$shnunc."')";
                    $insK = q($conn, $kaichila_query);
                    if ($insK === false) {
                        throw new Exception("Insert failed for shonu_kaichila: " . $conn->error);
                    }
                    error_log("Inserted new shonu_kaichila for referrer $referrer_id: motta = $reward_amount");
                }
            } else {
                error_log("No reward assigned for user $referred_id, deposit $deposit_amount (deposit: $deposit_amount, turnover: $total_bet, required: $required_bet)");
            }
        } // end deposits loop

        if ($user_has_reward) {
            $effective_users[$referred_id] = true;
        }
    } // end referred users loop

    q($conn, "SET FOREIGN_KEY_CHECKS = 1");
    $conn->commit();

    // Sum stored rewards in last 6 days from YOUR partner_rewards table
    $stored_rewards_query = "SELECT SUM(reward_amount) as total FROM partner_rewards 
                             WHERE user_id = '".$referrer_id."' 
                               AND last_updated >= '".$six_days_ago."'";
    $stored_rewards_result = q($conn, $stored_rewards_query);
    $total_reward = 0.0;
    if ($stored_rewards_result) {
        $total_reward = (float)($stored_rewards_result->fetch_assoc()['total'] ?? 0);
    }

    $data = [
        'configAmount' => "388.00",
        'numberOfInvitations' => $number_of_invitations,
        'effectiveQuantity' => count($effective_users),
        'totalAmount' => number_format($total_reward, 4, '.', ''),
        'invitationCode' => $invitation_code,
        'items' => $config_items,
        'days' => 6
    ];

    $res['data'] = $data;
    $res['code'] = 0;
    $res['msg'] = 'Succeed';
    $res['msgCode'] = 0;
    $res['serviceNowTime'] = $shnunc;
    http_response_code(200);
    echo json_encode($res);
    exit;

} catch (Exception $e) {
    $conn->rollback();
    q($conn, "SET FOREIGN_KEY_CHECKS = 1");
    error_log("Exception in partner reward processing: " . $e->getMessage());
    $res['code'] = 8;
    $res['msg'] = 'Transaction failed: ' . $e->getMessage();
    $res['msgCode'] = 7;
    http_response_code(500);
    echo json_encode($res);
    exit;
}
?>