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

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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id == 0) {
    header("Location: index.php?s=" . encrypt_url('mod=token&page=list_token'));
    exit;
}

// Fetch the Token
$sql = "SELECT w.*, m.CATEGORY_ID 
        FROM TBL_WEIGHBRIDGE_TICKETS w 
        JOIN TBL_MINES m ON w.MINE_ID = m.MINE_ID 
        WHERE w.TICKET_ID = $id AND w.STATUS = 'FIRST_WEIGHT'";
$result = $db->query($sql);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    header("Location: index.php?s=" . encrypt_url('mod=token&page=list_token') . "&status=invalid");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $second_wt   = (float)$_POST['second_weight'];
    $truck_meas  = $db->escape($_POST['truck_measurement']);
    $updated_by  = (int)$_SESSION['user_id'];
    
    // 1. Calculate Net Weight
    $net_weight = $second_wt - $data['FIRST_WEIGHT'];
    
    if ($net_weight <= 0) {
        $error = "Gross Weight must be greater than Tare Weight!";
    } else {
        // 2. Fetch Active Rate from Matrix
        $cat_id = $data['CATEGORY_ID'];
        $type_id = $data['TYPE_ID'];
        
        $rate_sql = "SELECT RATE_PER_TON FROM TBL_RATES 
                     WHERE CATEGORY_ID = $cat_id AND TYPE_ID = $type_id AND STATUS = 'ACTIVE'";
        $rate_res = $db->query($rate_sql);
        $rate_row = mysqli_fetch_assoc($rate_res);
        
        $rate_applied = $rate_row ? (float)$rate_row['RATE_PER_TON'] : 0;
        
        // 3. Assume Calculations (For Demo)
        $total_amount = $net_weight * $rate_applied;
        
        // Dummy Tax Rates
        $royalty = $net_weight * 150; // Assume Rs. 150 per ton
        $cess    = $net_weight * 50;  // Assume Rs. 50 per ton
        $excise  = $net_weight * 30;  // Assume Rs. 30 per ton
        $wht     = $total_amount * 0.02; // Assume 2% Withholding Tax
        
        $net_payable = $total_amount - ($royalty + $cess + $excise + $wht);

        // 4. Update Database
        $update_sql = "UPDATE TBL_WEIGHBRIDGE_TICKETS 
                       SET SECOND_WEIGHT = $second_wt,
                           SECOND_WEIGHT_TIME = CURRENT_TIMESTAMP,
                           NET_WEIGHT = $net_weight,
                           TRUCK_MEASUREMENT = '$truck_meas',
                           RATE_APPLIED = $rate_applied,
                           TOTAL_AMOUNT = $total_amount,
                           ROYALTY_AMOUNT = $royalty,
                           CESS_AMOUNT = $cess,
                           EXCISE_AMOUNT = $excise,
                           WHT_AMOUNT = $wht,
                           NET_PAYABLE = $net_payable,
                           STATUS = 'COMPLETED',
                           UPDATED_BY = $updated_by
                       WHERE TICKET_ID = $id";
                       
        if ($db->query($update_sql)) {
            // Redirect to the Multi-Print Dispatch Page
            header("Location: index.php?s=" . encrypt_url('mod=token&page=print_dispatch&id=' . $id));
            exit;
        }
    }
}
?>

<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-success"><i class="fas fa-weight-hanging mr-2"></i>Finalize Dispatch (Gross Weight)</h1>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            
            <?php if(isset($error)): ?>
                <div class="alert alert-danger font-weight-bold"><i class="fas fa-exclamation-triangle mr-2"></i><?php echo $error; ?></div>
            <?php endif; ?>

            <form action="" method="POST">
                <div class="card card-outline card-success shadow-sm" style="border-top: 4px solid #28a745;">
                    <div class="card-body">
                        
                        <div class="row mb-4 bg-light p-3 rounded border">
                            <div class="col-md-3">
                                <label class="text-muted text-uppercase mb-1" style="font-size: 12px;">Token No</label>
                                <h5 class="font-weight-bold text-dark"><?php echo htmlspecialchars($data['TICKET_NO']); ?></h5>
                            </div>
                            <div class="col-md-3">
                                <label class="text-muted text-uppercase mb-1" style="font-size: 12px;">Vehicle</label>
                                <h5 class="text-primary font-weight-bold"><i class="fas fa-truck mr-2"></i><?php echo htmlspecialchars($data['VEHICLE_NO']); ?></h5>
                            </div>
                            <div class="col-md-3">
                                <label class="text-muted text-uppercase mb-1" style="font-size: 12px;">Tare (Initial) Weight</label>
                                <h5 class="font-weight-bold text-danger"><?php echo number_format($data['FIRST_WEIGHT'], 2); ?> Tons</h5>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-6 form-group">
                                <label class="text-secondary text-uppercase font-weight-bold">Truck Measurement (L x W x H)</label>
                                <input type="text" name="truck_measurement" class="form-control form-control-lg" placeholder="e.g. 24 x 8 x 7" required>
                                <small class="text-muted">Required for the Urdu Delivery Order (Bilty).</small>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="p-3 bg-dark rounded text-center shadow">
                                    <label class="text-warning text-uppercase mb-2" style="letter-spacing: 2px;">Gross (Loaded) Weight</label>
                                    <div class="input-group">
                                        <input type="number" step="0.01" min="<?php echo $data['FIRST_WEIGHT'] + 0.1; ?>" name="second_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-success 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">
                        <a href="index.php?s=<?php echo encrypt_url('mod=token&page=list_token'); ?>" class="btn btn-default btn-lg mr-3 shadow-sm border"><i class="fas fa-times mr-2"></i> Cancel</a>
                        <button type="submit" class="btn btn-success btn-lg px-5 font-weight-bold shadow-sm">
                            <i class="fas fa-check-double mr-2"></i> DISPATCH & PRINT CHALLANS
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>