<?php
require_once("../layouts/members/head.php");
 if ($user_data['pan_print_service'] == "YES") { 
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
  $getresult = false;
  $getresults = true;
?>
<?php
if (isset($_POST['submit'])) {
    $getresult = true;
    $getresults = false;
    $panNumber = is_valid_pan($_POST['panNumber']) ?? '';
    if (!empty($panNumber)) {
    $order_id = order_txn_id();
    $amount = $user_data['pan_card_print_fee']/2;
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;
    
if ($old_balance >= $amount) {
    
$request = [
    'panNumber' => $panNumber,
    'order_id' => $order_id
];

$responseApi = panDetailsPrememium_run($request);
$response = json_decode($responseApi, true) ?? '';

if (isset($response['status']) && $response['status'] == '100') {
    $updateSuccess = db_update("members", ["balance" => $new_balance], " user_id='" . $user_data['user_id'] . "' ");

    if ($updateSuccess) {
        $insData = [
            'site_id'       => $site_data['site_id'],
            'user_id'       => $user_data['user_id'],
            'username'      => $user_data['username'],
            'name'          => $user_data['name'],
            'operator'      => $user_data['usertype'],
            'parent_id'     => $user_data['parent_id'],
            'order_id'      => $order_id,
            'service'       => "PANDETAILS",
            'type'          => "Debit",
            'account_number'=> $panNumber,
            'app_type'      => "PANDETAILS",
            'amount'        => $amount,
            'main_amount'   => $amount,
            'old_balance'   => $old_balance,
            'new_balance'   => $new_balance,
            'txn_id'        => $order_id,
            'ref_id'        => $response['name'],
            'description'   => "Rs.{$amount} Has Been Debit From Wallet for PAN DETAILS {$panNumber} for Pan Card Print Name: ",
            'date_time'     => current_timestamp(),
            'status'        => "Success"
        ];

        $insertId = db_insert("reports", $insData);
        if ($insertId) {
           $fields = [
               'name' => 'Name',
               'fathername' => 'Father',
               'dob' => 'DOB',
               'gender' => 'Gender',
               'aadhar' => 'UID',
               'address' => 'Address',
               'mobileNumber' => 'Mobile',
               'emailId' => 'Email'
           ];

           $whamessage = "Dear {$user_data['name']},\nYour Request for PAN *{$panNumber}* Details For Pan Card Print has been Complete.\n\n";

           foreach ($fields as $key => $label) {
               if (!empty($response[$key])) {
                   $whamessage .= "*$label*: {$response[$key]}\n";
               }
           }
           $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
            send_sms($user_data['mobile'],$whamessage);
          //   awal_alert_msg("Pan Details Fetched Successfully!", 'success');
        } else {
            awal_alert_msg("Insert Server Error!", 'error');
        }
    } else {
        awal_alert_msg("Balance debited from wallet but not updated in the database. Please contact support!", 'error');
    }
} else {
    awal_alert_msg($response['error'] ?? 'Server Down', 'error');
}
}else {
   alert_msg("Balance Low Please Recharge!", 'danger');
}
}else {
   alert_msg("Please Fill All Valid Details!", 'danger');
}
}
if (isset($_POST['savedata'])) {
    $order_id = order_txn_id();
    $amount = $user_data['pan_card_print_fee']/2;
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;
    
if ($old_balance >= $amount) {
    
    $name = $_POST['name'] ?? '';
    $fathername = $_POST['fathername'] ?? '';
    $panNumber = is_valid_pan($_POST['panNumber']) ?? '';
    $dob = $_POST['dobadhar'] ?? '';
    $gender = $_POST['gender'] ?? '';
if (!empty($name) && !empty($fathername) && !empty($panNumber) && !empty($dob) && !empty($gender)) {
    $base64Image = null;
    $base64Sign = null;
if (isset($_FILES['imageInput']) && $_FILES['imageInput']['error'] === UPLOAD_ERR_OK) {
    $imageFile = $_FILES['imageInput']['tmp_name'];
    $imageSize = $_FILES['imageInput']['size'];
    $imageType = mime_content_type($imageFile);
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
    if ($imageSize <= 102400 && in_array($imageType, $allowedTypes)) {
        $imageData = file_get_contents($imageFile);
        $base64Image = 'data:' . $imageType . ';base64,' . base64_encode($imageData);
    
if (isset($_FILES['signhkbInput']) && $_FILES['signhkbInput']['error'] === UPLOAD_ERR_OK) {
    $SignFile = $_FILES['signhkbInput']['tmp_name'];
    $SignSize = $_FILES['signhkbInput']['size'];
    $imageType = mime_content_type($SignFile);
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
    if ($SignSize <= 102400 && in_array($imageType, $allowedTypes)) {
        $SignData = file_get_contents($SignFile);
        $base64Sign = 'data:' . $imageType . ';base64,' . base64_encode($SignData);
    
    $updateSuccess = db_update("members", ["balance" => $new_balance], "user_id='{$user_data['user_id']}'");
    if ($updateSuccess) {
     $insData = [
         'site_id'       => $site_data['site_id'],
         'user_id'       => $user_data['user_id'],
         'username'      => $user_data['username'],
         'name'          => $user_data['name'],
         'operator'      => $user_data['usertype'],
         'parent_id'     => $user_data['parent_id'],
         'order_id'      => $order_id,
         'service'       => "PAN PRINT",
         'type'          => "Debit",
         'account_number'=> $panNumber,
         'app_type'      => "PAN PRINT",
         'amount'        => $amount,
         'main_amount'   => $amount,
         'old_balance'   => $old_balance,
         'new_balance'   => $new_balance,
         'txn_id'        => $order_id,
         'ref_id'        => $panNumber,
         'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$name} for PAN CARD PRINT By PAN ",
         'date_time'     => current_timestamp(),
         'status'        => "Success"
     ];

     $insertIds = db_insert("reports", $insData);
     if ($insertIds) {
         //successful insert in records
      } else {
          awal_alert_msg("Insert Server Error!", 'error');
      }
    
    $printData = array(
        'name' => $name,
        'fathername' => $fathername,
        'panNumber' => $panNumber,
        'username' => $user_data['username'],
        'dob' => $dob,
        'gender' => $gender,
        'imgdata' => $base64Image,
        'signdata' => $base64Sign,
    );

    $Mremark = 'Name: ' . $name . " - Pan Number: " . $panNumber;
    $insData = [
        'order_id'      => $order_id,
        'username'      => $user_data['username'],
        'name'          => $name,
        'idNumber'      => $panNumber,
        'service'       => "PAN PRINT",
        'date_time'     => current_timestamp(),
        'printData'     => base64_encode(str_replace("\\", "", json_encode($printData, JSON_UNESCAPED_UNICODE))),
        'photo'         => $base64Image,
    ];

    $insertId = db_insert("printRecords", $insData);
    
    if ($insertId) {
         awal_alert_msg("PAN Download Successful from '.$Mremark.'.", 'success');
        redirect('printRecord', 2000);
    } else {
         awal_alert_msg("Saving Data Error!", 'error');
     }
} else {
    awal_alert_msg("Balance debited from wallet but not updated in the database. Please contact support!", 'error');
}
} else {
        alert_msg("Invalid signature file. Please upload a JPG, JPEG, or PNG file under 100KB.File Type is ". $imageType, 'danger');
}
} else {
    alert_msg("No valid signature file uploaded. Please try again.", 'danger');
}
} else {
        alert_msg("Invalid image file. Please upload a JPG, JPEG, or PNG file under 100KB.File Type is ". $imageType, 'danger');
}
} else {
    alert_msg("No valid image file uploaded. Please try again.", 'danger');
}
} else {
   awal_alert_msg("Please Fill All Valid Details!", 'error');
}
} else {
   awal_alert_msg("Insufficient Wallet Balance!", 'error');
} 
}
?>

    <div class="col-md-4 mb-2 <?= isset($getresults) && $getresults ? '' : 'd-none' ?>">
      <div class="card text-danger">
        <div class="card-header bg-primary text-white py-2">
          <div class="d-flex align-items-center">
            <span class="mr-auto"><?= file_name() ?></span>
             <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()" > <i class="fas fa-arrow-left"></i> Back</button>
          </div>
        </div>
        <div class="p-3 text-dark">
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Pan Number</label>
                <input type="text" name="panNumber" placeholder="Enter PAN Number" maxlength="10" class="form-control" 
                pattern="^[A-Z]{5}[0-9]{4}[A-Z]{1}$" title="PAN number must be in the format of AAAAA1234A" oninput="this.value = this.value.toUpperCase()"
                onkeypress="if(this.value.length==10) return false;" required>
            </div>
            <div class="col-md-12 mb-3 d-flex justify-content-between">
              <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo isset($user_data['pan_card_print_fee']) ? $user_data['pan_card_print_fee'] : 0; ?></button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
<div class="container-xxl flex-grow-1 container-p-y <?= isset($getresult) && $getresult ? '' : 'd-none' ?>">
    <div class="row">
        <div class="col-lg-5">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0">PAN Details in English</h6>
                </div><form method="post" action="" id="myForm" enctype="multipart/form-data">
                <div class="card-body">
                        <div class="mb-3">
                            <label for="panNumber" class="form-label">PAN Number:</label>
                            <input type="text" class="form-control" id="panNumber" name="panNumber" maxlength="10" readonly value="<?php echo isset($panNumber) ? $panNumber : ''; ?>" placeholder="ABCDE1234F" autocomplete="off" required>
                            <small id="panError" class="text-danger" style="display:none;">Invalid PAN Number. Format: ABCDE1234F</small>
                        </div>
                        <div class="mb-3">
                            <label for="name" class="form-label">Full Name:</label>
                               <input type="text" class="form-control" name="name" id="name" readonly placeholder="ENTER NAME" 
                                   value="<?php echo isset($response['name']) ? strtoupper($response['name']) : ''; ?>" 
                                   autocomplete="off" required 
                                   oninput="this.value = this.value.toUpperCase();">
                        </div>
                        <div class="mb-3">
                            <label for="name" class="form-label">Father Name:</label>
                            <input type="text" class="form-control" name="fathername" id="fathername" placeholder="Enter father Name" oninput="this.value = this.value.toUpperCase();" value="<?php echo isset($response['fathername']) ? $response['fathername'] : ''; ?>" autocomplete="off" required>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="gender" class="form-label">Select Gender:</label>
                                <select class="form-control" id="gender" name="gender" required>
                                    <option value="">Select Gender</option>
                                    <option value="Male" <?php echo (isset($response['gender']) && $response['gender'] == 'Male') ? 'selected' : ''; ?>>Male</option>
                                    <option value="Female" <?php echo (isset($response['gender']) && $response['gender'] == 'Female') ? 'selected' : ''; ?>>Female</option>
                                    <option value="Transgender" <?php echo (isset($response['gender']) && $response['gender'] == 'Transgender') ? 'selected' : ''; ?>>Transgender</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="dobadhar" class="form-label">Date of Birth:</label>
                                <input class="form-control" name="dobadhar" id="dob" type="text" placeholder="01/01/2000" value="<?php echo isset($response['dob']) ? $response['dob'] : ''; ?>" autocomplete="off" required>
                            </div>
                        </div>
                    <button class="btn btn-primary" type="submit" name="savedata">PDF Download</button>
                </div>
            </div>
        </div>
        
        <div class="col-lg-2">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0 text-center">Photo</h6>
                </div>
                <div class="card-body text-center">
                    <div style="width: 150px; height: 150px; border: 1px solid #ccc; display: flex; align-items: center; justify-content: center; margin: auto;">
                        <img id="imagePreview" src="" alt="Selected Image" style="max-width: 100%; max-height: 100%; display: none;">
                    </div>
                    <input type="file" class="form-control mt-3" id="imageInput" name="imageInput" accept="image/*" onchange="previewImage()" required>
                    <small id="errorMessage" class="text-danger" style="display: none;">Please select a valid image file under 100KB.</small>
                </div>
            </div>
        </div>
        <div class="col-lg-2">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0 text-center">Signature</h6>
                </div>
                <div class="card-body text-center">
                    <div style="width: 150px; height: 150px; border: 1px solid #ccc; display: flex; align-items: center; justify-content: center; margin: auto;">
                        <img id="signhkbPreview" src="" alt="Selected Image" style="max-width: 100%; max-height: 100%; display: none;">
                    </div>
                    <input type="file" class="form-control mt-3" id="signhkbInput" name="signhkbInput" accept="image/*" onchange="previewSignhkb()" required>
                     <small id="errorMessages" class="text-danger" style="display: none;">Please select a valid image file under 100KB.</small>
                </div>
            </div>
        </div>
     </form>
    </div>
</div>
<script>
document.getElementById('panNumber').addEventListener('input', function () {
    let panInput = this.value.toUpperCase(); // Convert input to uppercase
    panInput = panInput.replace(/[^A-Z0-9]/g, ''); // Remove spaces and special characters
    this.value = panInput; // Set the sanitized input back to the field

    const panError = document.getElementById('panError');
    const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/; // PAN validation regex

    if (panRegex.test(panInput)) {
        panError.style.display = 'none'; // Hide error
        this.classList.remove('is-invalid'); // Remove invalid class
        this.classList.add('is-valid'); // Add valid class
    } else {
        panError.style.display = 'block'; // Show error
        this.classList.add('is-invalid'); // Add invalid class
        this.classList.remove('is-valid'); // Remove valid class
    }
});

  flatpickr("#dob", {
    dateFormat: "d/m/Y", 
    allowInput: true,   
    maxDate: "today",  
    onChange: function(selectedDates, dateStr, instance) {
      console.log("Selected date:", dateStr); 
    }
  });
</script>
<script>
  function closeModal() {
    $('#aadharDownloadModal').modal('hide');
  }
  function setModalSeenCookie() {
    document.cookie = "aadharDownloadModalSeen=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
  }
  function isModalSeen() {
    return document.cookie.indexOf("aadharDownloadModalSeen=true") !== -1;
  }
  $('#aadharDownloadModal').on('hidden.bs.modal', function () {
    setModalSeenCookie();
  });
  if (!isModalSeen()) {
    $(document).ready(function () {
      $('#aadharDownloadModal').modal('show');
    });
  }
  $('#modalHorizontalCarouselControls .carousel-control-next').on('click', function () {
    if ($('#modalHorizontalCarouselControls .carousel-inner .carousel-item:last').hasClass('active')) {
      closeModal();
    }
  });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script> 
<script>
function previewImage() {
    const input = document.getElementById('imageInput');
    const preview = document.getElementById('imagePreview');
    const errorMessage = document.getElementById('errorMessage');
    const file = input.files[0];

    if (file) {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        const maxSize = 100 * 1024; // 100 KB in bytes

        if (allowedTypes.includes(file.type)) {
            if (file.size <= maxSize) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    errorMessage.style.display = 'none';
                };
                reader.readAsDataURL(file);
            } else {
                errorMessage.textContent = 'File size must be less than 100 KB.';
                errorMessage.style.display = 'block';
                input.value = '';
                preview.src = '';
                preview.style.display = 'none';
            }
        } else {
            errorMessage.textContent = `Unsupported file type: ${file.type}. Only JPG, JPEG, or PNG images are allowed.`;
            errorMessage.style.display = 'block';
            input.value = '';
            preview.src = '';
            preview.style.display = 'none';
        }
    } else {
        preview.src = '';
        preview.style.display = 'none';
        errorMessage.style.display = 'none';
    }
}



function previewSignhkb() {
    const input = document.getElementById('signhkbInput');
    const preview = document.getElementById('signhkbPreview');
    const errorMessages = document.getElementById('errorMessages');
    const file = input.files[0];

    if (file) {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        const maxSize = 100 * 1024; // 50 KB in bytes

        if (allowedTypes.includes(file.type)) {
            if (file.size <= maxSize) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    errorMessages.style.display = 'none';
                };
                reader.readAsDataURL(file);
            } else {
                errorMessages.textContent = 'File size must be less than 100 KB.';
                errorMessages.style.display = 'block';
                input.value = '';
                preview.src = '';
                preview.style.display = 'none';
            }
        } else {
            errorMessages.textContent = 'Please upload a valid image (JPG, JPEG, or PNG).';
            errorMessages.style.display = 'block';
            input.value = '';
            preview.src = '';
            preview.style.display = 'none';
        }
    } else {
        preview.src = '';
        preview.style.display = 'none';
        errorMessages.style.display = 'none';
    }
}

</script>

<?php } else {
    require_once("404.php");
}
} else {
      awal_alert_msg('You Do Not Have Any Pan Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>