<?php
/**
 * modules/token/list_token.php
 * Weighbridge Token Management
 */

// 1. FETCH GLOBAL PERMISSIONS
$p = $GLOBALS['my_privs'] ?? ['can_view' => 0, 'can_add' => 0, 'can_edit' => 0, 'can_del' => 0];
if (in_array(1, $_SESSION['all_role_ids'] ?? [])) {
    $p = ['can_view' => 1, 'can_add' => 1, 'can_edit' => 1, 'can_del' => 1];
}

// 2. FETCH ACTIVE WEIGHBRIDGE TOKENS
$sql = "SELECT w.*, c.CONTRACTOR_NAME, m.MINE_NUMBER, b.BLOCK_NAME 
        FROM TBL_WEIGHBRIDGE_TICKETS w
        LEFT JOIN TBL_CONTRACTORS c ON w.CONTRACTOR_ID = c.CONTRACTOR_ID
        LEFT JOIN TBL_MINES m ON w.MINE_ID = m.MINE_ID
        LEFT JOIN TBL_BLOCKS b ON m.BLOCK_ID = b.BLOCK_ID
        ORDER BY w.TICKET_ID DESC LIMIT 1000";
$result = $db->query($sql);
?>

<style>
    .thead-wimas { background-color: #F4F7FA; color: #343a40; border-bottom: 2px solid #007bff; }
    .btn-white { background-color: #ffffff; }
    .dataTables_filter input { border-radius: 20px; border: 1px solid #ced4da; padding: 5px 12px; width: 250px !important; }
</style>

<div class="p-3">
    <section class="content-header px-0">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="font-weight-bold text-primary"><i class="fas fa-truck-moving mr-2"></i>Weighbridge Tokens</h1>
                </div>
                <div class="col-sm-6 text-right">
                    <?php if($p['can_add'] == 1): ?>
                    <a href="index.php?s=<?php echo encrypt_url('mod=token&page=add_token'); ?>" class="btn btn-primary shadow-sm btn-lg font-weight-bold">
                        <i class="fas fa-plus-circle mr-1"></i> GENERATE NEW TOKEN
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            <div class="card card-outline card-primary shadow-sm" style="border-top: 4px solid #007bff;">
                <div class="card-body p-0">
                    <div class="table-responsive p-3">
                        <table id="tokenTable" class="table table-hover table-striped mb-0" style="font-size: 0.9rem;">
                            <thead class="thead-wimas">
                                <tr>
                                    <th>Token / S.No</th>
                                    <th>Vehicle No.</th>
                                    <th>Contractor</th>
                                    <th>Mine / Block</th>
                                    <th class="text-right">Tare Wt. (In)</th>
                                    <th class="text-center">Status</th>
                                    <th class="text-center no-export">Operations</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($row = mysqli_fetch_assoc($result)): ?>
                                <tr>
                                    <td class="align-middle">
                                        <b class="text-primary"><?php echo htmlspecialchars($row['TICKET_NO']); ?></b><br>
                                        <small class="text-muted font-weight-bold">Daily S.No: <?php echo str_pad($row['DAILY_SERIAL'], 3, '0', STR_PAD_LEFT); ?></small>
                                    </td>
                                    <td class="align-middle font-weight-bold text-dark" style="font-size: 1.1rem;">
                                        <i class="fas fa-truck mr-1 text-secondary"></i> <?php echo htmlspecialchars($row['VEHICLE_NO']); ?>
                                    </td>
                                    <td class="align-middle"><?php echo htmlspecialchars($row['CONTRACTOR_NAME']); ?></td>
                                    <td class="align-middle">
                                        <span class="badge badge-info shadow-sm px-2 py-1"><?php echo htmlspecialchars($row['MINE_NUMBER']); ?></span><br>
                                        <small class="text-muted font-weight-bold"><?php echo htmlspecialchars($row['BLOCK_NAME']); ?></small>
                                    </td>
                                    <td class="align-middle text-right font-weight-bold">
                                        <?php echo number_format($row['FIRST_WEIGHT'], 2); ?>
                                    </td>
                                    <td class="text-center align-middle">
                                        <?php if ($row['STATUS'] == 'FIRST_WEIGHT'): ?>
                                            <span class="badge badge-warning px-3 py-2 shadow-sm"><i class="fas fa-spinner fa-spin mr-1"></i> IN TRANSIT</span>
                                        <?php elseif ($row['STATUS'] == 'COMPLETED'): ?>
                                            <span class="badge badge-success px-3 py-2 shadow-sm"><i class="fas fa-check-double mr-1"></i> DISPATCHED</span>
                                        <?php else: ?>
                                            <span class="badge badge-danger px-3 py-2 shadow-sm"><i class="fas fa-times mr-1"></i> CANCELLED</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td class="text-center align-middle no-export">
                                        <div class="btn-group shadow-sm">
                                            
                                            <!-- RE-PRINT TOKEN BUTTON (Visible to Viewers) -->
                                            <?php if($p['can_view'] == 1): ?>
                                            <a href="index.php?s=<?php echo encrypt_url('mod=token&page=print_token&id='.$row['TICKET_ID']); ?>" 
                                               target="_blank" class="btn btn-sm btn-white border text-dark" title="Print Token Slip" data-toggle="tooltip">
                                                <i class="fas fa-print"></i>
                                            </a>
                                            <?php endif; ?>

                                            <!-- SECOND WEIGHT BUTTON (Only visible if IN TRANSIT and user has edit rights) -->
                                            <?php if($row['STATUS'] == 'FIRST_WEIGHT' && $p['can_edit'] == 1): ?>
                                            <a href="index.php?s=<?php echo encrypt_url('mod=token&page=complete_token&id='.$row['TICKET_ID']); ?>" 
                                               class="btn btn-sm btn-success border font-weight-bold" title="Capture Second Weight" data-toggle="tooltip">
                                                <i class="fas fa-weight-hanging mr-1"></i> Gross
                                            </a>
                                            <?php endif; ?>

                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="assets/plugins/datatables-bs4/css/dataTables.bootstrap4.min.js">

<script>
window.addEventListener('load', function() {
    if (window.jQuery && $.fn.DataTable) {
        $('[data-toggle="tooltip"]').tooltip(); 
        $('#tokenTable').DataTable({
            "responsive": true, 
            "autoWidth": false, 
            "order": [[0, "desc"]], // Sort by Newest Tokens First
            "columnDefs": [{ "orderable": false, "targets": "no-export" }],
            "language": { "search": "<strong>Find Token/Vehicle:</strong>", "lengthMenu": "Show _MENU_ entries" }
        });
    }
});
</script>