<?php
/**
 * modules/contractors/edit_contractors.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=contractors&page=list_contractors') . "&status=access_denied");
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code     = strtoupper($db->escape($_POST['contractor_code']));
    $name     = ucwords(strtolower($db->escape($_POST['contractor_name'])));
    $person   = ucwords(strtolower($db->escape($_POST['contact_person'])));
    $mobile   = $db->escape($_POST['mobile_number']);
    $cnic     = $db->escape($_POST['cnic_number']);
    $ntn      = $db->escape($_POST['ntn_number']);
    $address  = $db->escape($_POST['address']);
    $status   = $db->escape($_POST['status']);
    $curr_usr = (int)$_SESSION['user_id'];

    $check_sql = "SELECT CONTRACTOR_ID FROM TBL_CONTRACTORS WHERE (CONTRACTOR_CODE = '$code' OR CONTRACTOR_NAME = '$name') AND CONTRACTOR_ID != $cid";
    if (mysqli_num_rows($db->query($check_sql)) > 0) {
        header("Location: index.php?s=" . encrypt_url("mod=contractors&page=edit_contractors&id=$cid") . "&status=duplicate");
        exit;
    }

    $sql = "UPDATE TBL_CONTRACTORS 
            SET CONTRACTOR_CODE = '$code',
                CONTRACTOR_NAME = '$name',
                CONTACT_PERSON = '$person',
                MOBILE_NUMBER = '$mobile',
                CNIC_NUMBER = '$cnic',
                NTN_NUMBER = '$ntn',
                ADDRESS = '$address',
                STATUS = '$status',
                UPDATED_BY = $curr_usr,
                UPDATED_DATE = CURRENT_TIMESTAMP
            WHERE CONTRACTOR_ID = $cid";
    
    if ($db->query($sql)) {
        header("Location: index.php?s=" . encrypt_url('mod=contractors&page=list_contractors') . "&status=updated");
        exit;
    }
}

$sql = "SELECT * FROM TBL_CONTRACTORS WHERE CONTRACTOR_ID = $cid";
$result = $db->query($sql);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    header("Location: index.php?s=" . encrypt_url('mod=contractors&page=list_contractors'));
    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-primary"><i class="fas fa-edit mr-2"></i>Edit Contractor</h1>
                </div>
                <div class="col-sm-6 text-right">
                    <a href="index.php?s=<?php echo encrypt_url('mod=contractors&page=list_contractors'); ?>" class="btn btn-default shadow-sm border">
                        <i class="fas fa-arrow-left mr-1"></i> Cancel Update
                    </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">Contractor Code <span class="text-danger">*</span></label>
                                <input type="text" name="contractor_code" class="form-control" value="<?php echo htmlspecialchars($data['CONTRACTOR_CODE']); ?>" required style="text-transform: uppercase;">
                            </div>
                            <div class="col-md-5 form-group">
                                <label class="text-secondary">Official Name / Syndicate <span class="text-danger">*</span></label>
                                <input type="text" name="contractor_name" class="form-control" value="<?php echo htmlspecialchars($data['CONTRACTOR_NAME']); ?>" required style="text-transform: capitalize;">
                            </div>
                            <div class="col-md-4 form-group">
                                <label class="text-secondary">Contact Person <span class="text-danger">*</span></label>
                                <input type="text" name="contact_person" class="form-control" value="<?php echo htmlspecialchars($data['CONTACT_PERSON']); ?>" required style="text-transform: capitalize;">
                            </div>

                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Mobile Number <span class="text-danger">*</span></label>
                                <input type="text" name="mobile_number" class="form-control mobile-mask" value="<?php echo htmlspecialchars($data['MOBILE_NUMBER']); ?>" maxlength="12" required>
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">CNIC Number</label>
                                <input type="text" name="cnic_number" class="form-control cnic-mask" value="<?php echo htmlspecialchars($data['CNIC_NUMBER']); ?>" maxlength="15">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">NTN Number</label>
                                <input type="text" name="ntn_number" class="form-control ntn-mask" value="<?php echo htmlspecialchars($data['NTN_NUMBER']); ?>" maxlength="9">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Status</label>
                                <select name="status" class="form-control">
                                    <option value="ACTIVE" <?php echo ($data['STATUS'] == 'ACTIVE') ? 'selected' : ''; ?>>ACTIVE</option>
                                    <option value="INACTIVE" <?php echo ($data['STATUS'] == 'INACTIVE') ? 'selected' : ''; ?>>INACTIVE</option>
                                </select>
                            </div>

                            <div class="col-md-12 form-group">
                                <label class="text-secondary">Registered Address</label>
                                <textarea name="address" class="form-control" rows="2"><?php echo htmlspecialchars($data['ADDRESS']); ?></textarea>
                            </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 CONTRACTOR
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>

<!-- Input Masking Script -->
<script>
    // 1. Mobile Number Mask (03XX-XXXXXXX)
    document.querySelector('.mobile-mask').addEventListener('input', function (e) {
        let x = e.target.value.replace(/\D/g, '').match(/(\d{0,4})(\d{0,7})/);
        e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2];
    });

    // 2. CNIC Mask (XXXXX-XXXXXXX-X)
    document.querySelector('.cnic-mask').addEventListener('input', function (e) {
        let x = e.target.value.replace(/\D/g, '').match(/(\d{0,5})(\d{0,7})(\d{0,1})/);
        e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
    });

    // 3. NTN Mask (XXXXXXX-X)
    document.querySelector('.ntn-mask').addEventListener('input', function (e) {
        let x = e.target.value.replace(/\D/g, '').match(/(\d{0,7})(\d{0,1})/);
        e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2];
    });
</script>