<?php
declare(strict_types=1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$title = 'История платежей';
require_once '../sys/sys.php';
require_once '../sys/db.php';
require_once '../sys/head.php';

if (!isset($_SESSION['admin'])) {
    echo '<div class="menu">Ошибка! Такой страницы не существует!</div>';
    require_once '../sys/foot.php';
    exit;
}

$max = 5;
$type = !empty($_GET['type']) ? htmlspecialchars($_GET['type']) : null;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;

switch ($type) {
    case 'ads':
        $countQuery = $pdo->query('SELECT COUNT(*) FROM reklama');
        $table = 'reklama';
        break;
    case 'iframe':
        $countQuery = $pdo->query('SELECT COUNT(*) FROM iframe');
        $table = 'iframe';
        break;
    default:
        $countQuery = false;
}

$totalItems = $countQuery ? $countQuery->fetchColumn() : 0;
$pages = $countQuery ? ceil($totalItems / $max) : 0;

if ($page < 1) $page = 1;
if ($pages > 0 && $page > $pages) $page = $pages;

$start = ($page - 1) * $max;
$query = [];

if ($countQuery && $totalItems > 0) {
    $sql = "SELECT * FROM `$table` ORDER BY `id` DESC LIMIT :limit OFFSET :offset";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':limit', $max, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $start, PDO::PARAM_INT);
    $stmt->execute();
    $query = $stmt->fetchAll();
}

echo '<div class="bg-index"><br/>
    <div class="title-page">
        <h2 style="color: #fff;">История платежей</h2>
    </div>
    <div class="container">
        <center>
            <p class="text-light" style="position: relative; z-index: 99; font-size: 120%;">
                История платежей системы <b>' . $_SERVER['HTTP_HOST'] . '</b>
            </p>
        </center>
    </div><br/>
</div><br/>
<div class="container">
    <div class="row">
        <div class="col-12">
            <div class="card bg-light">
                <div class="card-header text-center">Выберите тип истории платежей</div>
                <div class="card-body">
                    <div class="d-flex flex-column flex-md-row gap-2 gap-md-4 justify-content-center">
                        <a href="?type=iframe" class="text-center text-nowrap">
                            <div class="menu btn btn-outline-primary wow shake" style="white-space: normal; min-width: 100%; padding: 0.375rem 0.75rem;">
                                История покупок Iframe
                            </div>
                        </a>
                        <a href="?type=ads" class="text-center text-nowrap">
                            <div class="menu btn btn-outline-primary wow shake" style="white-space: normal; min-width: 100%; padding: 0.375rem 0.75rem;">
                                История покупок Реклама
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>';

if (!empty($query)) {
    echo '<div class="container"><br/>
        <center>
            <div class="row">
                <div class="col-md-12">
                    <div class="card bg-light">
                        <div class="card-header">Детали платежей</div>
                        <div class="card-body">';

    foreach ($query as $value) {
        echo '<div class="title">
                <p>URL: <a href="' . h($value['url'] ?? '') . '" target="_blank" style="color: black;">' . h($value['url'] ?? '') . '</a></p>
              
              <div class="menu">
                <p>Сумма: ' . ($value['summa'] ?? '') . '</p>
                <p>Создан: ' . ($value['created_at'] ?? $value['init'] ?? '') . '</p>
                <p>Конец: ' . ($value['expire'] ?? '') . '</p>
                <p>Система: ' . ($value['type_pay'] ?? 'Не указано') . '</p>
                <p>Статус: ' . ($value['status'] == 1 ? '<span style="color: green">Оплачен</span>' : '<span style="color: red">Ожидание</span>') . '</p></br>
              </div></div>';
    }

    echo '</div></div></div></center></div>';
    
    if ($pages > 0) {
        echo '<div class="pagination-container"><ul class="pagination">';
        
        if ($page > 1) {
            echo '<li class="page-item"><a class="page-link" href="?type='.$type.'&page='.($page-1).'">&laquo;</a></li>';
        } else {
            echo '<li class="page-item disabled"><span class="page-link">&laquo;</span></li>';
        }
        
        if ($pages == 1) {
            echo '<li class="page-item active"><span class="page-link">1</span></li>';
        } else {
            if ($page == 1) {
                echo '<li class="page-item active"><span class="page-link">1</span></li>';
            } else {
                echo '<li class="page-item"><a class="page-link" href="?type='.$type.'&page=1">1</a></li>';
            }
            
            $startRange = max(2, $page - 2);
            $endRange = min($pages - 1, $page + 2);
            
            if ($startRange > 2) {
                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
            
            for ($i = $startRange; $i <= $endRange; $i++) {
                if ($i == $page) {
                    echo '<li class="page-item active"><span class="page-link">'.$i.'</span></li>';
                } else {
                    echo '<li class="page-item"><a class="page-link" href="?type='.$type.'&page='.$i.'">'.$i.'</a></li>';
                }
            }
            
            if ($endRange < $pages - 1) {
                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
            
            if ($pages > 1) {
                if ($page == $pages) {
                    echo '<li class="page-item active"><span class="page-link">'.$pages.'</span></li>';
                } else {
                    echo '<li class="page-item"><a class="page-link" href="?type='.$type.'&page='.$pages.'">'.$pages.'</a></li>';
                }
            }
        }
        
        if ($page < $pages) {
            echo '<li class="page-item"><a class="page-link" href="?type='.$type.'&page='.($page+1).'">&raquo;</a></li>';
        } else {
            echo '<li class="page-item disabled"><span class="page-link">&raquo;</span></li>';
        }
        
        echo '</ul></div>';
    }
} elseif (!empty($type)) {
    echo '<div class="container">
        <div class="alert alert-warning">Платежей этого типа пока нет.</div>
    </div>';
}

if (!empty($_GET['type'])) {
    echo '<div class="container">
    <div class="row">
        <div class="col-lg-4 col-md-3"></div>
        <div class="col-lg-4 col-md-6">
            <div class="alert bg-light stat" style="margin-top: -35px;">
                <center><a href="/admin/history" class="btn btn-secondary">В историю</a></center>
            </div>
        </div>
    </div>
</div>';
} else {
    echo '<div class="row">
        <div class="col-lg-4 col-md-3"></div>
        <div class="col-lg-4 col-md-6">
            <div class="alert stat" style="margin-top: -20px;">
                <center><a href="/admin/" class="btn btn-secondary">Админ панель</a></center>
        </div>
    </div>
</div>';
}

function h($str = '') {
    return htmlspecialchars($str ?? '');
}

require_once '../sys/foot.php';
?>