<?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');

// Fix Database Encoding for Hindi/Regional languages in JSON
mysqli_set_charset($conn, "utf8mb4");
mysqli_query($conn, "SET NAMES 'utf8mb4'");
mysqli_query($conn, "SET CHARACTER SET 'utf8mb4'");

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

$uid = $_SESSION['user_id'];
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';

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

// Admin sees all details, Retailer sees only their own
$filter = ($utype == 'TitanAdmin') ? "" : "WHERE user_id = '$uid'";

// Count Total Records
$count_query = "SELECT COUNT(*) AS total FROM vehicle_challan_history $filter";
$count_result = $conn->query($count_query);
$total_records = 0;
if ($count_result && $row_count = $count_result->fetch_assoc()) {
    $total_records = $row_count['total'];
}

// 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
$query = "SELECT * FROM vehicle_challan_history $filter ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = $conn->query($query);

// 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-list-alt 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">Vehicle Challan <span class="text-info fw-medium">List</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="challan_check.php" class="btn btn-sm btn-primary shadow-none fw-bold"><i class="fas fa-search me-1"></i> New Check</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3 border-0 shadow-sm border-top border-4 border-primary">
    <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>Vehicle No.</th>
                        <th>Status / Msg</th>
                        <th>Records Found</th>
                        <th>Date & Time</th>
                        <th class="text-end pe-4">Action</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($result && $result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): 
                            
                            // Decode JSON to count pending and paid challans
                            $records = json_decode($row['full_data'], true);
                            $pending_count = isset($records['pending']) ? count($records['pending']) : 0;
                            $paid_count = isset($records['paid']) ? count($records['paid']) : 0;
                            $total_challans = $pending_count + $paid_count;
                            
                            // Secure JSON encode for the HTML data attribute
                            $secure_json_data = htmlspecialchars($row['full_data'], ENT_QUOTES, 'UTF-8');
                        ?>
                            <tr>
                                <td class="py-3 fw-bold text-900">#<?php echo $row['id']; ?></td>
                                <td>
                                    <span class="badge badge-subtle-primary fs-11 px-3 py-2 font-monospace border border-primary">
                                        <i class="fas fa-car-side me-1"></i> <?php echo htmlspecialchars($row['vehicle_no']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="text-success fw-semi-bold"><?php echo htmlspecialchars($row['message']); ?></span><br>
                                    <small class="text-danger fw-bold">₹<?php echo $row['total_amount']; ?></small>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-info fs-11 px-3 py-2 border border-info">
                                        <i class="fas fa-file-invoice me-1"></i> <?php echo $total_challans; ?> Challans
                                    </span>
                                </td>
                                <td class="text-600">
                                    <?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?>
                                </td>
                                <td class="text-end pe-4">
                                    <?php if($total_challans > 0): ?>
                                    <button class="btn btn-sm btn-falcon-primary fw-bold px-3 shadow-none" 
                                            data-json="<?php echo $secure_json_data; ?>" 
                                            data-vehicle="<?php echo htmlspecialchars($row['vehicle_no']); ?>" 
                                            onclick="viewDetails(this)">
                                        <i class="fas fa-eye me-1"></i> View Details
                                    </button>
                                    <?php else: ?>
                                    <span class="badge badge-subtle-secondary">No Data</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="py-4 text-500 fst-italic">No challan history found.</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>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    function viewDetails(btn) {
        let vehicleNo = btn.getAttribute('data-vehicle');
        let rawData = btn.getAttribute('data-json');
        
        let records = {};
        try {
            records = JSON.parse(rawData);
        } catch (e) {
            console.error("Invalid JSON data");
            return;
        }

        // Combine Pending and Paid challans into one array for the table
        let allChallans = [];
        if (records.pending && Array.isArray(records.pending)) {
            allChallans = allChallans.concat(records.pending);
        }
        if (records.paid && Array.isArray(records.paid)) {
            allChallans = allChallans.concat(records.paid);
        }

        // Build HTML Table dynamically
        let htmlTable = `
            <div class="text-start mb-2"><span class="badge bg-primary fs-10">Vehicle: ${vehicleNo}</span></div>
            <div class="table-responsive mt-2" style="max-height: 450px; overflow-y: auto;">
                <table class="table table-bordered table-sm fs-10 text-start align-middle">
                    <thead class="bg-200 text-900 position-sticky top-0 shadow-sm">
                        <tr>
                            <th class="text-center py-2">Sr.</th>
                            <th class="py-2" style="min-width: 140px;">Challan No & Date</th>
                            <th class="py-2">Amount & Status</th>
                            <th class="py-2">Accused Name</th>
                            <th class="py-2" style="min-width: 200px;">Offence Details</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        if (allChallans.length > 0) {
            allChallans.forEach((c, index) => {
                let badgeClass = (c.challan_status && c.challan_status.toUpperCase() === 'PAID') ? 'badge-subtle-success' : 'badge-subtle-danger';
                let offenceName = (c.offence_details && c.offence_details.offence_name) ? c.offence_details.offence_name : 'N/A';
                
                htmlTable += `
                    <tr>
                        <td class="text-center fw-bold text-600">${index + 1}</td>
                        <td>
                            <strong class="text-primary d-block">${c.challan_number || 'N/A'}</strong>
                            <small class="text-700 fw-semi-bold fs-11"><i class="far fa-calendar-alt me-1"></i> ${c.challan_date || ''} ${c.challan_time || ''}</small>
                        </td>
                        <td>
                            <strong class="text-danger d-block fs-11">₹${c.challan_amount || '0'}</strong>
                            <span class="badge ${badgeClass} fs-10 px-2 py-1 mt-1">${c.challan_status || 'UNKNOWN'}</span>
                        </td>
                        <td class="text-700 fw-semi-bold">
                            ${c.accused_name || 'N/A'}
                        </td>
                        <td class="text-700" style="white-space: normal;">
                            <i class="fas fa-exclamation-triangle text-warning me-1"></i> ${offenceName}
                        </td>
                    </tr>
                `;
            });
        } else {
            htmlTable += `<tr><td colspan="5" class="text-center py-3">No Detailed Data Available</td></tr>`;
        }

        htmlTable += `</tbody></table></div>`;

        // Pop-up show karna
        Swal.fire({
            title: `<h5 class="mb-0 text-primary"><i class="fas fa-car-crash me-2"></i>Challan Details</h5>`,
            html: htmlTable,
            width: '950px', // Thoda bada popup taaki details clear dikhe
            confirmButtonText: 'Close Window',
            customClass: { confirmButton: 'btn btn-primary shadow-none px-4' },
            buttonsStyling: false
        });
    }
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>