<?php
/**
 * modules/contractors/add_contractors.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=contractors&page=list_contractors') . "&status=access_denied");
    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'";
    if (mysqli_num_rows($db->query($check_sql)) > 0) {
        header("Location: index.php?s=" . encrypt_url('mod=contractors&page=add_contractors') . "&status=duplicate");
        exit;
    }

    $sql = "INSERT INTO TBL_CONTRACTORS 
            (CONTRACTOR_CODE, CONTRACTOR_NAME, CONTACT_PERSON, MOBILE_NUMBER, CNIC_NUMBER, NTN_NUMBER, ADDRESS, STATUS, CREATED_BY) 
            VALUES 
            ('$code', '$name', '$person', '$mobile', '$cnic', '$ntn', '$address', '$status', $curr_usr)";
    
    if ($db->query($sql)) {
        header("Location: index.php?s=" . encrypt_url('mod=contractors&page=list_contractors') . "&status=added");
        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-plus-circle mr-2"></i>Register 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> Back to List
                    </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" placeholder="e.g. SYN-001" 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" placeholder="Legal Company 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" placeholder="Manager/Munshi Name" 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" placeholder="03XX-XXXXXXX" 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" placeholder="XXXXX-XXXXXXX-X" 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" placeholder="XXXXXXX-X" 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">ACTIVE</option>
                                    <option value="INACTIVE">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" placeholder="Full postal 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-save mr-2"></i> SAVE 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>