<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];

// ---------------- PAGINATION LOGIC START ----------------
$limit = 15; // Ek page par 15 data show karega
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) { $page = 1; }
$offset = ($page - 1) * $limit;

// Requirement: Admin ho ya Retailer, sabko sirf apna data dikhega
$count_query = "SELECT COUNT(*) AS total FROM aadhar_to_pan_history WHERE user_id = ?";
$stmt_count = $conn->prepare($count_query);
$stmt_count->bind_param("s", $uid);
$stmt_count->execute();
$count_result = $stmt_count->get_result();
$total_records = 0;

if ($count_result && $row_count = $count_result->fetch_assoc()) {
    $total_records = $row_count['total'];
}
$stmt_count->close();

// Total Pages calculation
$total_pages = ceil($total_records / $limit);
if ($page > $total_pages && $total_pages > 0) { 
    $page = $total_pages; 
    $offset = ($page - 1) * $limit; 
}

// Paginated Data Query (Optimized for memory performance)
$query = "SELECT * FROM aadhar_to_pan_history WHERE user_id = ? ORDER BY id DESC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("sii", $uid, $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();

// Entries dynamic calculation text
$start_entry = $total_records == 0 ? 0 : $offset + 1;
$end_entry = min($offset + $limit, $total_records);
// ---------------- PAGINATION LOGIC END ----------------
?>

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-primary-subtle shadow-none me-3">
                        <span class="fas fa-clipboard-list text-primary fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-primary fs-10 mb-0">History Log</h6>
                        <h4 class="text-primary fw-bold mb-0">Aadhar to Mask PAN <span class="text-warning fw-medium">Records</span></h4>
                    </div>
                </div>
                <div class="col-md-auto">
                    <a href="aadhaar_mask.php" class="btn btn-sm btn-warning shadow-none fw-bold"><i class="fas fa-search me-1"></i> New Search</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3 border-0 shadow-sm border-top border-4 border-warning">
    <div class="card-body p-0">
        <div class="table-responsive scrollbar">
            <table class="table table-sm table-striped fs-10 mb-0 text-center align-middle">
                <thead class="bg-200 text-900">
                    <tr>
                        <th class="py-2">#ID</th>
                        <th>Aadhaar No.</th>
                        <th>Masked PAN</th>
                        <th>System Message</th>
                        <th>Provider</th>
                        <th>Date & Time</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($result && $result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td class="py-2 fw-bold text-900">#<?php echo $row['id']; ?></td>
                                <td>
                                    <span class="badge badge-subtle-secondary fs-11 px-3 py-2 font-monospace text-700">
                                        <?php echo htmlspecialchars($row['aadhar_no']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-success fs-10 px-2 py-1 border border-success">
                                        <i class="fas fa-id-card me-1"></i> <?php echo htmlspecialchars($row['mask_pan']); ?>
                                    </span>
                                </td>
                                <td class="text-start px-3" style="max-width: 250px;">
                                    <small class="text-700 fw-semi-bold"><?php echo htmlspecialchars($row['message']); ?></small>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-primary fs-10 px-2 py-1">
                                        <?php echo htmlspecialchars($row['provider']); ?>
                                    </span>
                                </td>
                                <td class="text-700"><?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?></td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="py-4 text-500 fst-italic">No records found. Try searching for a PAN first.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card-footer d-flex align-items-center justify-content-between py-2 border-top bg-100">
        <p class="mb-0 fs-10 text-700 fw-semi-bold">
            Showing <?php echo $start_entry; ?> to <?php echo $end_entry; ?> of <?php echo $total_records; ?> entries
        </p>
        <?php if ($total_pages > 1): ?>
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                    <a class="page-link shadow-none" href="?page=<?php echo $page - 1; ?>" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                
                <?php 
                $start_loop = max(1, $page - 2);
                $end_loop = min($total_pages, $page + 2);
                for ($i = $start_loop; $i <= $end_loop; $i++): 
                ?>
                    <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                        <a class="page-link shadow-none" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                    <a class="page-link shadow-none" href="?page=<?php echo $page + 1; ?>" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
    </div>

<?php 
if (isset($stmt)) { $stmt->close(); }
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>