<?php
session_start();

require("../includes/db_connect.php");
$accountId = $_SESSION['usr_accountId'];


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ($_POST['redeem_code'] != "" ) {

        $accountId = $_SESSION['usr_accountId'];
        $redeem_code = $_POST['redeem_code'];
        // $redeem_id = $_POST['redeem_id'];

        $allcount_query = "SELECT * FROM redeem_code WHERE redeem_code = ? and status = 'created' ";
        $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
        $allcount_fetch->execute([$redeem_code]);
        $allcount = $allcount_fetch->rowCount();
        
        $url = "http://api.coinlayer.com/api/live?access_key=0f2d82a65368cd8ffd5faf501845884c&symbols=BTC,ETH";
        $jsonData = json_decode(file_get_contents($url), true);
        $btcRate = $jsonData['rates']['BTC'] ?? 1;
        $ethRate = $jsonData['rates']['ETH'] ?? 1;

        if ($allcount > 0) {
            $allcount_fetch = $allcount_fetch->fetchAll();

            if($allcount_fetch[0]['status'] == "created"){

                $account_type = $allcount_fetch[0]['account_type'];
                $redeem_amount = $allcount_fetch[0]['amount'];
                $temp_amount = $allcount_fetch[0]['amount'];
                $redeem_currency = $allcount_fetch[0]['currency'];
                
                if ($redeem_currency == "BTC") {
                    $redeem_amount = round(($temp_amount * $btcRate), 2);
                }else if ($redeem_currency == "ETH") {
                    $redeem_amount = round(($temp_amount * $ethRate), 2);
                }
                $update_balance = false;
                $datetime = date('Y-m-d H:i:s');
                $nbl = "";

                if($account_type == "monthly-account"){
                    $balance_sql = "SELECT * FROM monthly_trading_balances WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();
                    foreach ($account_balances as $key => $value) {
                        $usr_balance = $value['trade_amount'];
                        $acc_balance = round($usr_balance, 2);
                        $new_balance = round(($acc_balance + $redeem_amount), 2);
                        $new_balance_sql = "UPDATE monthly_trading_balances SET trade_amount=? WHERE accountId=?";
                        $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                    }
                    if ($update_balance) {
                        
                        $inv_sql = "INSERT INTO monthly_trade_history (accountId, type, trade_amount) VALUES (?,?,?)";
                        $create_inv = $conn->prepare($inv_sql)->execute([$accountId, "Trade (Monthly)", $redeem_amount]);
                        $trade_id = $conn->lastInsertId();
                        
                        if ($create_inv) {
                            $trans_sql = "INSERT INTO monthly_trade_transactions (accountId, type, trade_amount, profit, recent_profit, trade_history_id) VALUES (?,?,?,?,?,?)";
                            $create_trans = $conn->prepare($trans_sql)->execute([$accountId, "+Redeem Gift", $redeem_amount, "0.00", "0.00", $trade_id]);
                        }
                    }
                    

                } else if($account_type == "quarterly-account"){
                    
                    $balance_sql = "SELECT * FROM quarterly_trading_balances WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();
                    
                    if (count($account_balances) > 0) {
                        
                        foreach ($account_balances as $key => $value) {
                            $usr_balance = $value['trade_amount'];
                            $acc_balance = round($usr_balance, 2);
                            $new_balance = round(($acc_balance + $redeem_amount), 2);
                            $new_balance_sql = "UPDATE quarterly_trading_balances SET trade_amount=? WHERE accountId=?";
                            $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                        }
                        
                    }else {
                        
                        $sql = "SELECT * FROM users WHERE accountId=? LIMIT 1";
                        $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                        $sth->execute([$accountId]);
                        $history = $sth->fetchAll();
                        
                        if (count($history) > 0) {
                            
                            $quarterly_trading_balances_sql = "INSERT INTO quarterly_trading_balances (accountId, profit, trade_amount, withdrawn) VALUES (?,?,?,?)";
                            $update_balance = $conn->prepare($quarterly_trading_balances_sql)->execute([$accountId, 0.00, $redeem_amount, 0.00]);
                            
                        }
                        
                    }
                    
                    if ($update_balance) {
                        $inv_sql = "INSERT INTO quarterly_trade_history (accountId, type, trade_amount) VALUES (?,?,?)";
                        $create_inv = $conn->prepare($inv_sql)->execute([$accountId, "Trade (Quarterly)", $redeem_amount]);
                        $trade_id = $conn->lastInsertId();
                        
                        if ($create_inv) {
                            
                            $trans_sql = "INSERT INTO quarterly_trade_transactions (accountId, type, trade_amount, profit, recent_profit, trade_history_id) VALUES (?,?,?,?,?,?)";
                            $create_trans = $conn->prepare($trans_sql)->execute([$accountId, "+Redeem Gift", $redeem_amount, "0.00", "0.00", $trade_id]);
                        }   
                    }

                } else if($account_type == "annually-account"){

                    $balance_sql = "SELECT * FROM annual_trading_balances WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();

                    foreach ($account_balances as $key => $value) {
                        $usr_balance = $value['trade_amount'];
                        $acc_balance = round($usr_balance, 2);
                        $new_balance = round(($acc_balance + $redeem_amount), 2);
                        $new_balance_sql = "UPDATE annual_trading_balances SET trade_amount=? WHERE accountId=?";
                        $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                    }

                    $inv_sql = "INSERT INTO annual_trade_history (accountId, type, trade_amount) VALUES (?,?,?)";
                    $create_inv = $conn->prepare($inv_sql)->execute([$accountId, "Trade (Annually)", $redeem_amount]);
                    $trade_id = $conn->lastInsertId();
                    
                    if ($create_inv) {
                        /*$trans_sql = "INSERT INTO annual_trade_transactions (accountId, type, trade_amount, profit, recent_profit, trade_history_id, recent_date, date) VALUES (?,?,?,?,?,?,?,?)";
                        $create_trans = $conn->prepare($trans_sql)->execute([$accountId, "+Redeem Gift", $redeem_amount, "0.00", "0.00", $trade_id, $datetime, $datetime]);*/
                        
                        $trans_sql = "INSERT INTO annual_trade_transactions (accountId, type, trade_amount, profit, recent_profit, trade_history_id) VALUES (?,?,?,?,?,?)";
                        $create_trans = $conn->prepare($trans_sql)->execute([$accountId, "+Redeem Gift", $redeem_amount, "0.00", "0.00", $trade_id]);
                    }
                    
                } else if($account_type == "bonus-account"){
                    $balance_sql = "SELECT * FROM bonus_account_balances WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();

                    foreach ($account_balances as $key => $value) {
                        $usr_balance = $value['total_bonus'];
                        $acc_balance = round($usr_balance, 2);
                        $new_balance = round(($acc_balance + $redeem_amount), 2);
                        $new_balance_sql = "UPDATE bonus_account_balances SET total_bonus=? WHERE accountId=?";
                        $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                    }

                    $req_sql = "INSERT INTO bonus_account_transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";
                    $trans_name = "+Redeem Gift";
                    $type = "Approved";
                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $trans_name, $redeem_amount, $type, 1]);
                } else if($account_type == "wallet-account"){
                    $balance_sql = "SELECT * FROM wallet WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();

                    foreach ($account_balances as $key => $value) {
                        $usr_balance = $value['balance'];
                        $acc_balance = round($usr_balance, 2);
                        $new_balance = round(($acc_balance + $redeem_amount), 2);
                        $new_balance_sql = "UPDATE wallet SET balance=? WHERE accountId=?";
                        $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                    }
                    
                } else if($account_type == "community-bot-account"){
                    $balance_sql = "SELECT * FROM bot_trading_balances WHERE accountId=? LIMIT 1";
                    $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $balance_sth->execute([$accountId]);
                    $account_balances = $balance_sth->fetchAll();
                    foreach ($account_balances as $key => $value) {
                        $usr_balance = $value['trade_amount'];
                        $acc_balance = round($usr_balance, 2);
                        $new_balance = round(($acc_balance + $redeem_amount), 2);
                        $new_balance_sql = "UPDATE bot_trading_balances SET trade_amount=? WHERE accountId=?";
                        $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);
                    }
                    if ($update_balance) {
                        $inv_sql = "INSERT INTO bot_trade_history (accountId, type, trade_amount) VALUES (?,?,?)";
                        $create_inv = $conn->prepare($inv_sql)->execute([$accountId, "Trade (Community Bot)", $redeem_amount]);
                        $trade_id = $conn->lastInsertId();
                        
                        if ($create_inv) {
                            $trans_sql = "INSERT INTO bot_trade_transactions (accountId, type, trade_amount, profit, recent_profit, trade_history_id) VALUES (?,?,?,?,?,?)";
                            $create_trans = $conn->prepare($trans_sql)->execute([$accountId, "+Redeem Gift", $redeem_amount, "0.00", "0.00", $trade_id]);
                        }
                    }
                }

                if ($update_balance) {
                    $update_redeem = "UPDATE redeem_code SET status=?, availed_date=?,account_id=?  WHERE redeem_code = ? ";
                    $update_redeem = $conn->prepare($update_redeem)->execute(["claimed", date("Y-m-d H:i:s"),$accountId,$redeem_code]);
                    if ($update_redeem) {

                        $transaction_type = "";

                        switch ($account_type) {
                            case 'monthly-account':
                                $transaction_type = "Monthly";
                                break;
                            case 'quarterly-account':
                                $transaction_type = "Quarterly";
                                break;
                            case 'annually-account':
                                $transaction_type = "Annually";
                                break;
                            case 'bonus-account':
                                $transaction_type = "Bonus";
                                break;
                            case 'wallet-account':
                                $transaction_type = "Wallet";
                                break;
                            case 'community-bot-account':
                                $transaction_type = "Community Bot";
                                break;
                            default:
                                break;
                        }

                        $req_sql = "INSERT INTO transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";
                        $create_history = $conn->prepare($req_sql)->execute([$accountId, $transaction_type, $redeem_amount, "+Redeem Gift", 1]);
                    
                        die("success");
                    } else {
                        die("An unexpected error occurred. Please try again.");
                    }
                } else {
                    die("An unexpected error occurred. Please try again.");
                }

            }else{
                die('Code already claimed');
            }
        } else {
            die('Please enter valid code');
        }
    } else {
        die('Invalid information.');
    }
} else {
    die('Invalid request.');
}