<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

include('header.php');

$user_id = $udata['id'];
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Check if table exists, create if not
$tableCheck = mysqli_query($ahk_conn, "SHOW TABLES LIKE 'manual_service_transactions'");
if(mysqli_num_rows($tableCheck) == 0) {
    mysqli_query($ahk_conn, "CREATE TABLE IF NOT EXISTS `manual_service_transactions` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) NOT NULL,
      `service_name` varchar(255) NOT NULL,
      `transaction_id` varchar(100) NOT NULL,
      `amount` decimal(10,2) NOT NULL,
      `status` enum('Pending','Completed','Rejected') DEFAULT 'Pending',
      `transaction_date` datetime DEFAULT CURRENT_TIMESTAMP,
      `details` text DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `user_id` (`user_id`),
      KEY `status` (`status`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}

// Fetch records
$query = "SELECT * FROM manual_service_transactions 
          WHERE user_id = ? 
          ORDER BY transaction_date DESC 
          LIMIT ? OFFSET ?";
$stmt = mysqli_prepare($ahk_conn, $query);
mysqli_stmt_bind_param($stmt, "iii", $user_id, $limit, $offset);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

// Get total count
$countQuery = "SELECT COUNT(*) as total FROM manual_service_transactions WHERE user_id = ?";
$countStmt = mysqli_prepare($ahk_conn, $countQuery);
mysqli_stmt_bind_param($countStmt, "i", $user_id);
mysqli_stmt_execute($countStmt);
$totalResult = mysqli_fetch_assoc(mysqli_stmt_get_result($countStmt));
$totalRecords = $totalResult['total'];
$totalPages = ceil($totalRecords / $limit);

// Get stats
$statsQuery = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status='Pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status='Completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status='Rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(amount) as total_amount
    FROM manual_service_transactions WHERE user_id = ?";
$statsStmt = mysqli_prepare($ahk_conn, $statsQuery);
mysqli_stmt_bind_param($statsStmt, "i", $user_id);
mysqli_stmt_execute($statsStmt);
$stats = mysqli_fetch_assoc(mysqli_stmt_get_result($statsStmt));
?>

<style>
.history-wrapper {
    padding: 20px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    border-radius: 16px;
    padding: 25px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.08);
    display: flex;
    align-items: center;
    gap: 20px;
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0,0,0,0.12);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
}

.stat-icon.total { background: linear-gradient(135deg, #667eea, #764ba2); }
.stat-icon.pending { background: linear-gradient(135deg, #f39c12, #e74c3c); }
.stat-icon.completed { background: linear-gradient(135deg, #11998e, #38ef7d); }
.stat-icon.rejected { background: linear-gradient(135deg, #e74c3c, #c0392b); }

.stat-info h3 {
    margin: 0;
    font-size: 28px;
    font-weight: 700;
    color: #2d3436;
}

.stat-info p {
    margin: 5px 0 0;
    color: #636e72;
    font-size: 14px;
}

.history-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.08);
    overflow: hidden;
}

.history-card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px 25px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.history-card-header h4 {
    margin: 0;
    font-weight: 600;
}

.history-card-body {
    padding: 0;
}

.history-item {
    padding: 20px 25px;
    border-bottom: 1px solid #f1f3f4;
    display: flex;
    align-items: center;
    justify-content: space-between;
    transition: all 0.3s ease;
}

.history-item:hover {
    background: #f8f9fa;
}

.history-item:last-child {
    border-bottom: none;
}

.history-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.history-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
}

.history-info h6 {
    margin: 0 0 5px;
    font-weight: 600;
    color: #2d3436;
}

.history-info small {
    color: #636e72;
}

.history-right {
    text-align: right;
}

.history-amount {
    font-size: 18px;
    font-weight: 700;
    color: #2d3436;
}

.badge-status {
    display: inline-block;
    padding: 6px 15px;
    border-radius: 25px;
    font-size: 12px;
    font-weight: 600;
    margin-top: 5px;
}

.badge-pending {
    background: linear-gradient(135deg, #ffeaa7, #fdcb6e);
    color: #d35400;
}

.badge-completed {
    background: linear-gradient(135deg, #d4edda, #c3e6cb);
    color: #155724;
}

.badge-rejected {
    background: linear-gradient(135deg, #f8d7da, #f5c6cb);
    color: #721c24;
}

.empty-state {
    text-align: center;
    padding: 60px 30px;
}

.empty-state i {
    font-size: 80px;
    color: #dfe6e9;
    margin-bottom: 20px;
}

.empty-state h4 {
    color: #636e72;
    margin-bottom: 10px;
}

.empty-state p {
    color: #b2bec3;
}

.pagination-wrapper {
    padding: 20px 25px;
    display: flex;
    justify-content: center;
}

.pagination .page-link {
    border: none;
    padding: 10px 18px;
    margin: 0 3px;
    border-radius: 10px;
    color: #667eea;
    font-weight: 500;
    transition: all 0.3s ease;
}

.pagination .page-link:hover {
    background: #667eea;
    color: white;
}

.pagination .page-item.active .page-link {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

@media (max-width: 768px) {
    .history-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    .history-right {
        text-align: left;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
</style>

<div class="page-wrapper">
    <div class="page-content history-wrapper">
        
        <!-- Stats Grid -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon total"><i class="fas fa-list"></i></div>
                <div class="stat-info">
                    <h3><?php echo $stats['total'] ?? 0; ?></h3>
                    <p>Total Transactions</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon pending"><i class="fas fa-clock"></i></div>
                <div class="stat-info">
                    <h3><?php echo $stats['pending'] ?? 0; ?></h3>
                    <p>Pending</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon completed"><i class="fas fa-check-circle"></i></div>
                <div class="stat-info">
                    <h3><?php echo $stats['completed'] ?? 0; ?></h3>
                    <p>Completed</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon rejected"><i class="fas fa-times-circle"></i></div>
                <div class="stat-info">
                    <h3><?php echo $stats['rejected'] ?? 0; ?></h3>
                    <p>Rejected</p>
                </div>
            </div>
        </div>

        <!-- History Card -->
        <div class="history-card">
            <div class="history-card-header">
                <h4><i class="fas fa-history"></i> Print History</h4>
                <span class="badge bg-light text-dark">Total: ₹<?php echo number_format($stats['total_amount'] ?? 0, 2); ?></span>
            </div>
            <div class="history-card-body">
                <?php if(mysqli_num_rows($result) > 0): ?>
                    <?php while($row = mysqli_fetch_assoc($result)): ?>
                        <div class="history-item">
                            <div class="history-left">
                                <div class="history-icon">
                                    <i class="fas fa-print"></i>
                                </div>
                                <div class="history-info">
                                    <h6><?php echo htmlspecialchars($row['service_name']); ?></h6>
                                    <small>
                                        <i class="fas fa-hashtag"></i> <?php echo htmlspecialchars($row['transaction_id']); ?> | 
                                        <i class="fas fa-calendar"></i> <?php echo date('d M Y, h:i A', strtotime($row['transaction_date'])); ?>
                                    </small>
                                </div>
                            </div>
                            <div class="history-right">
                                <div class="history-amount">₹<?php echo number_format($row['amount'], 2); ?></div>
                                <?php
                                $statusClass = 'badge-pending';
                                if($row['status'] == 'Completed') $statusClass = 'badge-completed';
                                elseif($row['status'] == 'Rejected') $statusClass = 'badge-rejected';
                                ?>
                                <span class="badge-status <?php echo $statusClass; ?>"><?php echo $row['status']; ?></span>
                            </div>
                        </div>
                    <?php endwhile; ?>

                    <?php if($totalPages > 1): ?>
                        <div class="pagination-wrapper">
                            <nav>
                                <ul class="pagination mb-0">
                                    <?php if($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page-1; ?>">
                                                <i class="fas fa-chevron-left"></i>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php 
                                    $startPage = max(1, $page - 2);
                                    $endPage = min($totalPages, $page + 2);
                                    for($i = $startPage; $i <= $endPage; $i++): 
                                    ?>
                                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if($page < $totalPages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page+1; ?>">
                                                <i class="fas fa-chevron-right"></i>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-history"></i>
                        <h4>No Print History Found</h4>
                        <p>Your print transactions will appear here once you start using services.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
    </div>
</div>

<?php include('../admin/footers.php'); ?>