<?php
session_start();

require("../includes/db_connect.php");

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

    if ((!empty($_POST['page'])) && (!empty($_POST['search_id']))) {

        if ($conn) {
            try {

                $page = $_POST['page'];
                $search_id = $_POST['search_id'];

                $no_of_records_per_page = 50;
                $offset = ($page - 1) * $no_of_records_per_page;

                $allcount_query = "SELECT * FROM redeem_code ORDER BY redeem_code.date DESC";
                $allcount_fetch = $conn->prepare($allcount_query, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $allcount_fetch->execute();

                // Calculate total pages
                $allcount = $allcount_fetch->rowCount();
                $totalPages = ceil($allcount / $no_of_records_per_page);

                // Fetch history

                if ($search_id != "default") {

                    $sql = "SELECT * FROM redeem_code WHERE ? IN(redeem_code.account_id, redeem_code.redeem_code) ORDER BY redeem_code.date DESC LIMIT $offset, $no_of_records_per_page";
                    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $sth->execute([$search_id]);
                } else {
                    $sql = "SELECT * FROM redeem_code ORDER BY redeem_code.date DESC LIMIT $offset, $no_of_records_per_page";
                    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $sth->execute();
                }


                $history = $sth->fetchAll();

                $account_balances_history = "";

                if (count($history) > 0) {
                    foreach ($history as $key => $value) {
                        $id = $value['id'];
                        $account_id = $value['account_id'];
                        $redeem_code = $value['redeem_code'];
                        $amount = "$".number_format($value['amount']);
                        $currency = $value['currency'];
                        $status = $value['status'];
                        $date = $value['date'];
                        $availed_date = $value['availed_date'];
                        
                        if ($currency != "USD") {
                            $amount = round($value['amount'], 8);
                        }


                        $delete_btn = "";
                        if (is_null($availed_date)) {
                            $delete_btn = "<b class='btn btn-danger mr-2' onclick='deleteRedeem(\"$id\")'>Delete</b>";
                        }else{
                            $delete_btn = "<b class='btn mr-2' style='background-color:#f5f1f1;'>Claimed</b>";
                        }

                        $account_balances_history .= "<tr'>
                        <td>$account_id</td>
                        <td>$redeem_code</td>
                        <td>$amount</td>
                        <td>$currency</td>
                        <td>$status</td>
                        <td>$date</td>
                        <td>$availed_date</td>
                        <td>$delete_btn</td>
                        </tr>";
                    }

                    $response = array(
                        'history' => $account_balances_history,
                        'total_pages' => $totalPages,
                    );

                    echo (json_encode($response));
                } else {
                    echo "empty";
                }
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}


function convertDate($date)
{
    $dt = str_replace('/', '-', $date);

    return date('Y-m-d', strtotime($dt));
}