<?php
session_start();
require("../includes/db_connect.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['page']) && !empty($_POST['dateFrom']) && !empty($_POST['dateTo'])) {
        if ($conn) {
            try {
                $page = intval($_POST['page']);
                $dateFrom = convertDate($_POST['dateFrom']);
                $dateTo = convertDate($_POST['dateTo']);

                $no_of_records_per_page = 50;
                $offset = ($page - 1) * $no_of_records_per_page;
                $accountId = $_SESSION['usr_accountId'];

                // Get total count of referred users
                $allcount_query = "SELECT COUNT(*) FROM users WHERE referrer = ? AND (DATE(date) BETWEEN ? AND ?)";
                $allcount_fetch = $conn->prepare($allcount_query);
                $allcount_fetch->execute([$accountId, $dateFrom, $dateTo]);
                $allcount = $allcount_fetch->fetchColumn();
                $totalPages = ceil($allcount / $no_of_records_per_page);

                // Fetch referred users along with their purchased bots
                $sql = "SELECT accountId, fullname, date FROM users WHERE referrer = ? AND (DATE(date) BETWEEN ? AND ?) 
                        ORDER BY date DESC LIMIT ?, ?";
                $sth = $conn->prepare($sql);
                $sth->bindParam(1, $accountId, PDO::PARAM_INT);
                $sth->bindParam(2, $dateFrom, PDO::PARAM_STR);
                $sth->bindParam(3, $dateTo, PDO::PARAM_STR);
                $sth->bindParam(4, $offset, PDO::PARAM_INT);
                $sth->bindParam(5, $no_of_records_per_page, PDO::PARAM_INT);
                $sth->execute();
                $history = $sth->fetchAll();

                $referral_history = "";

                if (!empty($history)) {
                    foreach ($history as $value) {
                        $user_Id = htmlspecialchars($value['accountId']);
                        $user_fullName = htmlspecialchars($value['fullname']);
                        $user_date = new DateTime($value['date']);
                        $dis_date = $user_date->format('d/m/Y');

                        // Fetch purchased bots
                        $sql = "SELECT type FROM purchased_bots WHERE accountId = ? LIMIT 1";
                        $sth = $conn->prepare($sql);
                        $sth->execute([$user_Id]);
                        $result = $sth->fetch(PDO::FETCH_ASSOC);
                        $user_bots = $result ? htmlspecialchars($result['type']) : "User has no active bots.";

                        $referral_history .= "<tr>
                            <td>$user_Id</td>
                            <td>$user_fullName</td>
                            <td>$user_bots</td>
                        </tr>";
                    }

                    // Send response as JSON
                    $response = [
                        'history' => $referral_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)
{
    return date('Y-m-d', strtotime(str_replace('/', '-', $date)));
}
