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

// Set group_concat_max_len to handle long bot lists
$conn->exec("SET SESSION group_concat_max_len = 1000000");

$accountId = $_SESSION['usr_accountId']; // Logged-in user ID

$pageno = isset($_GET['pageno']) ? max(1, intval($_GET['pageno'])) : 1;
$rowperpage = 50;
$offset = ($pageno - 1) * $rowperpage;

// Count the number of referrals
$countQuery = "SELECT COUNT(*) FROM users WHERE referrer = :accountId";
$sth = $conn->prepare($countQuery);
$sth->execute([':accountId' => $accountId]);
$totalRows = intval($sth->fetchColumn());
$totalPages = ceil($totalRows / $rowperpage);
$isReferrer = $totalRows > 0;

// Fetch referred users along with their purchased bots
$sql = "SELECT u.accountId, u.fullname, u.referrer,
               COALESCE(GROUP_CONCAT(pb.type SEPARATOR ', '), 'User has no active bots.') AS user_bots
        FROM users u
        LEFT JOIN purchased_bots pb ON u.accountId = pb.accountId
        WHERE u.referrer = :accountId
        GROUP BY u.accountId, u.fullname, u.referrer
        ORDER BY u.date DESC
        LIMIT :rowperpage OFFSET :offset";

$sth = $conn->prepare($sql);
$sth->bindValue(':accountId', $accountId, PDO::PARAM_STR);
$sth->bindValue(':rowperpage', (int)$rowperpage, PDO::PARAM_INT);
$sth->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
$sth->execute();
$history = $sth->fetchAll();

// Build Referral History Table
$referral_history = "";
if (!empty($history) && $isReferrer) {
    foreach ($history as $value) {
        $user_Id = htmlspecialchars($value['accountId']);
        $user_fullName = htmlspecialchars($value['fullname']);
        $user_bots = htmlspecialchars($value['user_bots']);

        $referral_history .= "<tr>
        <td>$user_Id</td>
        <td>$user_fullName</td>
        <td>$user_bots</td>
        </tr>";
    }
} else {
    $referral_history = "<tr><td colspan='3' class='tx-color-03 tx-normal text-center'>You have not referred anyone.</td></tr>";
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Referrals</title>
    <?php require_once("includes/header.php"); ?>

    <div class="content ht-100v pd-0">
        <div class="content-header center">
            <img src="../img/logo-white.png" class="aside-logo" style="width: 160px;" />
        </div><!-- content-header -->

        <div class="content-body">
            <div class="container pd-x-0">
                <div class="d-sm-flex align-items-center justify-content-between mg-b-20 mg-lg-b-25 mg-xl-b-30">
                    <div>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb breadcrumb-style1 mg-b-10">
                                <li class="breadcrumb-item"><a href="account">Dashboard</a></li>
                            </ol>
                        </nav>
                        <h4 class="mg-b-0 tx-spacing--1">Referrals</h4>
                    </div>

                </div>

                <div class="row row-xs">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">

                                <div class="row col-xl-12">
                                    <div class="col-md-6 row">
                                        <div class="col-md-6">
                                            <label>From</label>

                                            <input type="text" id="dateFrom" class="form-control"
                                                placeholder="DD/MM/YYYY" value="<?php echo ($dateFrom) ?>">
                                        </div><!-- col -->
                                        <div class="col-md-6">
                                            <label>To</label>

                                            <input type="text" id="dateTo" class="form-control" placeholder="DD/MM/YYYY"
                                                value="<?php echo ($dateTo) ?>">

                                        </div><!-- col -->
                                    </div>
                                </div>

                                <div class="table-responsive" style="margin-top: 30px">
                                    <table class="table table-centered table-nowrap mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>ID</th>
                                                <th>Full Name</th>
                                                <th>Active Bots</th>
                                            </tr>
                                        </thead>
                                        <tbody id="referral_history">
                                            <?php echo ($referral_history); ?>
                                        </tbody>
                                    </table>
                                    <input type="hidden" id="history_page" value="1">
                                    <input type="hidden" id="total_pages" value="<?php echo ($totalPages); ?>">
                                    <input type="hidden" id="all_history" value="<?php echo ($allcount); ?>">
                                    <input type="hidden" id="loading_status" value="loaded">
                                </div>
                                <div class="col-md-10" style="margin-left: auto; margin-right: auto; margin-top: 20px">
                                    <div class="" style="float: right;">
                                        <nav aria-label="Page navigation example">
                                            <ul id="pagination" class="pagination pagination-circle mg-b-0" <?php if ($totalPages < 2) {
                                                                                                                echo "style='display: none'";
                                                                                                            } ?>>
                                                <li id="prev_history" class="page-item <?php if ($pageno <= 1) {
                                                                                            echo 'disabled';
                                                                                        } ?>">
                                                    <a class="page-link page-link-icon"
                                                        href="javascript:function previous() { return false; }"><i
                                                            data-feather="chevron-left"></i></a>
                                                </li>
                                                <li id="next_history" class="page-item <?php if ($pageno >= $totalPages) {
                                                                                            echo 'disabled';
                                                                                        } ?>">
                                                    <a class="page-link page-link-icon"
                                                        href="javascript:function next() { return false; }"><i
                                                            data-feather="chevron-right"></i></a>
                                                </li>
                                            </ul>
                                        </nav>
                                    </div><!-- df-example -->
                                </div>

                            </div>
                        </div>
                    </div>
                </div><!-- row -->
            </div><!-- container -->
        </div>
    </div>

    <?php require_once("includes/footer.php"); ?>
    <script type="text/javascript">
    $(document).ready(function() {
        var classes = $("#referrals").prop('class');
        $("#referrals").prop('class', classes + ' active pcoded-trigger');
    });
    </script>
    <script src="../js/referrals.js"></script>

    </body>

</html>