<?php
/**
 * modules/token/add_token.php
 */

$p = $GLOBALS['my_privs'] ?? ['can_add' => 0];
if (in_array(1, $_SESSION['all_role_ids'] ?? [])) { $p['can_add'] = 1; }

if ($p['can_add'] == 0) {
    header("Location: index.php?s=" . encrypt_url('mod=token&page=list_token') . "&status=access_denied");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vehicle_no = strtoupper($db->escape($_POST['vehicle_no']));
    $exp_tons   = !empty($_POST['expected_tons']) ? (float)$_POST['expected_tons'] : "NULL";
    $first_wt   = (float)$_POST['first_weight'];
    
    $driver_name   = ucwords(strtolower($db->escape($_POST['driver_name'])));
    $driver_mobile = $db->escape($_POST['driver_mobile']);
    
    $contractor_id = (int)$_POST['contractor_id'];
    $contractor_pw = $db->escape($_POST['contractor_password']);
    
    $mine_id       = (int)$_POST['mine_id'];
    $type_id       = (int)$_POST['type_id'];
    $created_by    = (int)$_SESSION['user_id'];

    // 1. Calculate Daily Serial Number for today
    $serial_sql = "SELECT IFNULL(MAX(DAILY_SERIAL), 0) + 1 AS NEXT_SERIAL 
                   FROM TBL_WEIGHBRIDGE_TICKETS 
                   WHERE DATE(FIRST_WEIGHT_TIME) = CURDATE()";
    $serial_res = $db->query($serial_sql);
    $serial_row = mysqli_fetch_assoc($serial_res);
    $daily_serial = $serial_row['NEXT_SERIAL'];

    // 2. Generate Unique Token Number (e.g., TK-20260614-001)
    $date_prefix = date('Ymd');
    $padded_serial = str_pad($daily_serial, 3, '0', STR_PAD_LEFT);
    $ticket_no = "TK-" . $date_prefix . "-" . $padded_serial;

    // 3. Insert Record
    $sql = "INSERT INTO TBL_WEIGHBRIDGE_TICKETS 
            (TICKET_NO, DAILY_SERIAL, VEHICLE_NO, EXPECTED_TONS, DRIVER_NAME, DRIVER_MOBILE, 
             CONTRACTOR_ID, CONTRACTOR_PASSWORD, MINE_ID, TYPE_ID, FIRST_WEIGHT, STATUS, CREATED_BY) 
            VALUES 
            ('$ticket_no', $daily_serial, '$vehicle_no', $exp_tons, '$driver_name', '$driver_mobile', 
             $contractor_id, '$contractor_pw', $mine_id, $type_id, $first_wt, 'FIRST_WEIGHT', $created_by)";
    
    if ($db->query($sql)) {
        // Safe Fallback: Fetch the ID using the Unique Ticket No we just generated
        $id_check_sql = "SELECT TICKET_ID FROM TBL_WEIGHBRIDGE_TICKETS WHERE TICKET_NO = '$ticket_no'";
        $id_res = $db->query($id_check_sql);
        $id_row = mysqli_fetch_assoc($id_res);
        $new_id = $id_row['TICKET_ID'];
        
        // Send them directly to the Print Slip page
        header("Location: index.php?s=" . encrypt_url('mod=token&page=print_token&id=' . $new_id));
        exit;
    }
}

// Fetch Master Lookups
$cont_res = $db->query("SELECT CONTRACTOR_ID, CONTRACTOR_NAME, CONTRACTOR_CODE FROM TBL_CONTRACTORS WHERE STATUS = 'ACTIVE'");
$mines_res = $db->query("SELECT m.MINE_ID, m.MINE_NUMBER, b.BLOCK_NAME FROM TBL_MINES m JOIN TBL_BLOCKS b ON m.BLOCK_ID = b.BLOCK_ID WHERE m.STATUS = 'ACTIVE'");
$types_res = $db->query("SELECT TYPE_ID, TYPE_NAME FROM TBL_COAL_TYPES WHERE STATUS = 'ACTIVE'");
?>

<link rel="stylesheet" href="assets/plugins/select2/css/select2.min.css">
<link rel="stylesheet" href="assets/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">

<!-- TRUCK ANIMATION CSS -->
<style>
    #truckLoader {
        display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(255, 255, 255, 0.95); z-index: 9999; flex-direction: column;
        justify-content: center; align-items: center; overflow: hidden;
    }
    .road-track {
        width: 100%; max-width: 600px; height: 8px; background: #343a40; position: relative; border-radius: 4px;
    }
    .truck-icon {
        position: absolute; bottom: 5px; left: -80px; font-size: 65px; color: #007bff;
        animation: driveTruck 1.8s cubic-bezier(0.4, 0, 0.2, 1) infinite;
    }
    .exhaust {
        position: absolute; bottom: 20px; left: -90px; width: 10px; height: 10px; background: #ccc; border-radius: 50%;
        animation: smoke 1.8s infinite; opacity: 0;
    }
    @keyframes driveTruck { 0% { left: -80px; } 100% { left: 100%; } }
    @keyframes smoke { 0% { opacity: 0; transform: scale(1) translateY(0); } 50% { opacity: 1; transform: scale(2) translateY(-20px); } 100% { opacity: 0; transform: scale(3) translateY(-40px); } }
</style>

<!-- TRUCK ANIMATION OVERLAY -->
<div id="truckLoader">
    <h2 class="text-primary font-weight-bold mb-5" style="letter-spacing: 1px;">Dispatching Truck to Loading Zone...</h2>
    <div class="road-track">
        <i class="fas fa-truck-moving truck-icon shadow-sm"></i>
        <div class="exhaust"></div>
    </div>
    <h5 class="text-muted mt-5 font-italic">Generating Secure Token...</h5>
</div>

<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-ticket-alt mr-2"></i>Generate Inbound Token</h1>
                </div>
                <div class="col-sm-6 text-right">
                    <a href="index.php?s=<?php echo encrypt_url('mod=token&page=list_token'); ?>" class="btn btn-default shadow-sm border">
                        <i class="fas fa-arrow-left mr-1"></i> Back to List
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            <!-- onsubmit triggers the animation -->
            <form action="" method="POST" onsubmit="return showTruckAnimation();">
                <div class="card card-outline card-primary shadow-sm" style="border-top: 4px solid #007bff;">
                    <div class="card-body">
                        
                        <!-- VEHICLE INFO -->
                        <h5 class="text-primary border-bottom pb-2 mb-3"><i class="fas fa-truck mr-2"></i>Vehicle & Driver Details</h5>
                        <div class="row">
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Vehicle Number <span class="text-danger">*</span></label>
                                <input type="text" name="vehicle_no" class="form-control form-control-lg font-weight-bold text-primary" placeholder="e.g. KHI-1234" required style="text-transform: uppercase;">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Expected Tons</label>
                                <input type="number" step="0.01" name="expected_tons" class="form-control form-control-lg" placeholder="0.00">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Driver Name</label>
                                <input type="text" name="driver_name" class="form-control" placeholder="Driver Name" style="text-transform: capitalize;">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Driver Mobile</label>
                                <input type="text" name="driver_mobile" class="form-control" placeholder="03XX-XXXXXXX" maxlength="12">
                            </div>
                        </div>

                        <!-- ASSIGNMENTS -->
                        <h5 class="text-primary border-bottom pb-2 mt-4 mb-3"><i class="fas fa-clipboard-list mr-2"></i>Loading Assignments</h5>
                        <div class="row">
                            <div class="col-md-4 form-group">
                                <label class="text-secondary">Contractor / Syndicate <span class="text-danger">*</span></label>
                                <select name="contractor_id" class="form-control select2" required>
                                    <option value="">-- Search Contractor --</option>
                                    <?php while($c = mysqli_fetch_assoc($cont_res)): ?>
                                        <option value="<?php echo $c['CONTRACTOR_ID']; ?>"><?php echo htmlspecialchars($c['CONTRACTOR_CODE'] . " - " . $c['CONTRACTOR_NAME']); ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2 form-group">
                                <label class="text-secondary">Cont. Password</label>
                                <input type="text" name="contractor_password" class="form-control" placeholder="Security PIN">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Target Mine & Block <span class="text-danger">*</span></label>
                                <select name="mine_id" class="form-control select2" required>
                                    <option value="">-- Select Destination --</option>
                                    <?php while($m = mysqli_fetch_assoc($mines_res)): ?>
                                        <option value="<?php echo $m['MINE_ID']; ?>"><?php echo htmlspecialchars($m['BLOCK_NAME'] . " - " . $m['MINE_NUMBER']); ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Coal Type <span class="text-danger">*</span></label>
                                <select name="type_id" class="form-control select2" required>
                                    <option value="">-- Select --</option>
                                    <?php while($t = mysqli_fetch_assoc($types_res)): ?>
                                        <option value="<?php echo $t['TYPE_ID']; ?>"><?php echo htmlspecialchars($t['TYPE_NAME']); ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>

                        <!-- WEIGHBRIDGE TARE WEIGHT -->
                        <div class="row mt-4">
                            <div class="col-md-4 offset-md-4">
                                <div class="p-4 bg-dark rounded text-center shadow">
                                    <label class="text-warning text-uppercase mb-2" style="letter-spacing: 2px;">Tare (Initial) Weight</label>
                                    <div class="input-group">
                                        <input type="number" step="0.01" min="0" name="first_weight" class="form-control form-control-lg text-center font-weight-bold text-dark" style="font-size: 24px; height: 60px;" placeholder="0.00" required>
                                        <div class="input-group-append">
                                            <span class="input-group-text bg-secondary text-white font-weight-bold" style="font-size: 20px;">TONS</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                    <div class="card-footer bg-white text-center p-4">
                        <button type="submit" class="btn btn-primary btn-lg px-5 font-weight-bold shadow-sm" style="font-size: 1.2rem;">
                            <i class="fas fa-print mr-2"></i> SAVE & GENERATE TOKEN
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>

<script src="assets/plugins/select2/js/select2.full.min.js"></script>
<script>
    $(function () {
        $('.select2').select2({ theme: 'bootstrap4' });
    });

    // Fire the animation and let the form submit normally
    function showTruckAnimation() {
        document.getElementById('truckLoader').style.display = 'flex';
        // Return true allows the POST request to continue to the server while the animation plays
        return true; 
    }
</script>