<?php
/**
 * modules/token/edit_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;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vehicle_no = strtoupper($db->escape($_POST['vehicle_no']));
    $exp_tons   = !empty($_POST['expected_tons']) ? (float)$_POST['expected_tons'] : "NULL";
    
    $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'];
    $first_wt      = (float)$_POST['first_weight'];
    $updated_by    = (int)$_SESSION['user_id'];

    $sql = "UPDATE TBL_WEIGHBRIDGE_TICKETS 
            SET VEHICLE_NO = '$vehicle_no',
                EXPECTED_TONS = $exp_tons,
                DRIVER_NAME = '$driver_name',
                DRIVER_MOBILE = '$driver_mobile',
                CONTRACTOR_ID = $contractor_id,
                CONTRACTOR_PASSWORD = '$contractor_pw',
                MINE_ID = $mine_id,
                TYPE_ID = $type_id,
                FIRST_WEIGHT = $first_wt,
                UPDATED_BY = $updated_by
            WHERE TICKET_ID = $id AND STATUS = 'FIRST_WEIGHT'";
            
    if ($db->query($sql)) {
        header("Location: index.php?s=" . encrypt_url('mod=token&page=list_token') . "&status=updated");
        exit;
    }
}

$sql = "SELECT * FROM TBL_WEIGHBRIDGE_TICKETS WHERE TICKET_ID = $id";
$result = $db->query($sql);
$data = mysqli_fetch_assoc($result);

if (!$data || $data['STATUS'] != 'FIRST_WEIGHT') {
    header("Location: index.php?s=" . encrypt_url('mod=token&page=list_token'));
    exit;
}

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

<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-edit mr-2"></i>Edit Token: <?php echo $data['TICKET_NO']; ?></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> Cancel
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            <form action="" method="POST">
                <div class="card card-outline card-primary shadow-sm" style="border-top: 4px solid #007bff;">
                    <div class="card-body">
                        
                        <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" value="<?php echo htmlspecialchars($data['VEHICLE_NO']); ?>" 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" value="<?php echo $data['EXPECTED_TONS']; ?>">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Driver Name</label>
                                <input type="text" name="driver_name" class="form-control" value="<?php echo htmlspecialchars($data['DRIVER_NAME']); ?>">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Driver Mobile</label>
                                <input type="text" name="driver_mobile" class="form-control" value="<?php echo htmlspecialchars($data['DRIVER_MOBILE']); ?>">
                            </div>
                        </div>

                        <div class="row mt-3">
                            <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" required>
                                    <?php while($c = mysqli_fetch_assoc($cont_res)): ?>
                                        <option value="<?php echo $c['CONTRACTOR_ID']; ?>" <?php echo ($data['CONTRACTOR_ID'] == $c['CONTRACTOR_ID']) ? 'selected' : ''; ?>>
                                            <?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" value="<?php echo htmlspecialchars($data['CONTRACTOR_PASSWORD']); ?>">
                            </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" required>
                                    <?php while($m = mysqli_fetch_assoc($mines_res)): ?>
                                        <option value="<?php echo $m['MINE_ID']; ?>" <?php echo ($data['MINE_ID'] == $m['MINE_ID']) ? 'selected' : ''; ?>>
                                            <?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" required>
                                    <?php while($t = mysqli_fetch_assoc($types_res)): ?>
                                        <option value="<?php echo $t['TYPE_ID']; ?>" <?php echo ($data['TYPE_ID'] == $t['TYPE_ID']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($t['TYPE_NAME']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>

                        <div class="row mt-3 border-top pt-3">
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Tare (Initial) Weight <span class="text-danger">*</span></label>
                                <input type="number" step="0.01" name="first_weight" class="form-control font-weight-bold text-dark" value="<?php echo $data['FIRST_WEIGHT']; ?>" required>
                            </div>
                        </div>

                    </div>
                    <div class="card-footer bg-white text-right p-3">
                        <button type="submit" class="btn btn-primary px-5 font-weight-bold shadow-sm">
                            <i class="fas fa-sync mr-2"></i> UPDATE TOKEN
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>