<?php
require_once("../layouts/members/head.php");
if ($user_data['psa_active'] == "YES") {
function generate_branch_id($user_id) {
    $prefix = "PSA" . date('ymd');
    $rand   = strtoupper(substr(base_convert(bin2hex(random_bytes(6)), 16, 36), 0, 6));
    return $prefix . $rand;
}

function generate_unique_psa_id($user_id) {
    for ($i = 0; $i < 5; $i++) {
        $candidate = generate_branch_id($user_id);
        $exists = db_fetch_array("members", "psa_id = '{$candidate}'");
        if (!$exists) return $candidate;
    }
    return generate_branch_id($user_id) . "-" . strtoupper(substr(dechex((int)$user_id), 0, 4));
}

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_psa'])) {
        $newPsa = generate_unique_psa_id($user_data['user_id']);
        $ok = db_update("members", ["psa_id" => $newPsa], "user_id='{$user_data['user_id']}'");

        if ($ok) {
            $user_data['psa_id'] = $newPsa;
            awal_alert_msg("Branch ID generated successfully: {$newPsa}", 'success');
            // header("Location: " . $_SERVER['REQUEST_URI']); exit;
        } else {
            awal_alert_msg("Failed to generate Branch ID. Please try again or contact support.", 'error');
        }
    }

if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {

if (empty($user_data['psa_id'])): ?>
    <div class="row">
        <div class="col-md-6 mb-2">
            <div class="card border-warning">
                <div class="card-header bg-warning text-dark py-2">
                    <div class="d-flex align-items-center">
                        <span class="mr-auto">Branch ID Required</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">
                    <p class="mb-3">
                        You need a <strong>Branch ID (PSA ID)</strong> to proceed with PAN operations.
                        Click the button below to generate it for your account.
                    </p>
                    <form method="post">
                        <button type="submit" name="generate_psa" class="btn btn-primary"
                                onclick="return confirm('Generate Branch ID now?');">
                            Generate Branch ID
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php
    require_once("../layouts/members/foot.php");
    exit;
endif; 
?>
<div class="row">
    <div class="col-md-6 mb-2">
      <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">
          <?php
          $apiResponseData = null;
          if (isset($_POST['submit'])) {
              $phoneNumber    = $_POST['phoneNumber'] ?? '';
              $name           = $_POST['name'] ?? '';
              $gender         = $_POST['gender'] ?? '';
              $emailID        = $_POST['emailID'] ?? '';
              $applicationMode= $_POST['applicationMode'] ?? '';
              $applicationType= $_POST['applicationType'] ?? '';
              $nsdlOrderID    = "QUICKNSDL".order_txn_id();
              $branchCode     = $user_data['psa_id'] ?? '';

              if (!empty($phoneNumber) && !empty($name) && !empty($gender) && !empty($emailID) && !empty($applicationMode) && !empty($applicationType) 
              && !empty($nsdlOrderID) && !empty($branchCode)) {
                  
                  $amount = $user_data['pan_apply_fee'];
                  $old_balance = $user_data['balance'];

                  if ($old_balance >= $amount) {
                      $request = [
                          'phoneNumber'     => $phoneNumber,
                          'name'            => $name,
                          'gender'          => $gender,
                          'emailID'         => $emailID,
                          'applicationMode' => $applicationMode,
                          'applicationType' => $applicationType,
                          'orderID'         => $nsdlOrderID,
                          'branchCode'      => $branchCode, // PSA/Branch ID guaranteed now
                      ];
                           
                          $new_balance = $old_balance - $amount;
                          
                          $responseApi = NSDL_pan_apply_correction_api_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'      => $response['nsdl_orderid'],
                                      'service'       => "NSDL_PAN",
                                      'type'          => "Debit",
                                      'account_number'=> $response['phone'],
                                      'app_type'      => $response['applicationTypefull'] ?? " NSDL_PAN",
                                      'amount'        => $amount,
                                      'main_amount'   => $amount,
                                      'old_balance'   => $old_balance,
                                      'new_balance'   => $new_balance,
                                      'txn_id'        => $response['nsdl_orderid'],
                                      'ref_id'        => $response['phone'],
                                      'description'   => "Rs.{$amount} Has Been Debit From Wallet for {$response['applicationTypefull']} Name {$response['name']} Number ",
                                      'date_time'     => current_timestamp(),
                                      'status'        => "Pending",
                                  ];

                                  $insertId = db_insert("reports", $insData);
                                  if ($insertId) {
                                      
                                    $printData = array(
                                        'name'=> isset($response['name']) && !empty($response['name']) ? $response['name'] : 'NA',
                                        'gender'    => isset($response['gender']) && !empty($response['gender']) ? $response['gender'] : '',
                                        'phone'  => isset($response['phone']) && !empty($response['phone']) ? $response['phone'] : $phoneNumber,
                                        'email' => isset($response['email']) && !empty($response['email']) ? $response['email'] : '',
                                        'nsdl_orderid' => isset($response['nsdl_orderid']) && !empty($response['nsdl_orderid']) ? $response['nsdl_orderid'] : 'NA',
                                        'applicationType' => isset($response['applicationType']) && !empty($response['applicationType']) ? $response['applicationType'] : '',
                                        'applicationTypefull' => isset($response['applicationTypefull']) && !empty($response['applicationTypefull']) ? $response['applicationTypefull'] : '',
                                        'mode' => isset($response['mode']) && !empty($response['mode']) ? $response['mode'] : '',
                                        'branchCode' => isset($response['branchCode']) && !empty($response['branchCode']) ? $response['branchCode'] : '',
                                        'redirectUrl' => isset($response['redirectUrl']) && !empty($response['redirectUrl']) ? $response['redirectUrl'] : '',
                                        'username'      => $user_data['username'],
                                    );
                                    $phone   = isset($response['phone']) && !empty($response['phone']) ? $response['phone'] : $phoneNumber;
                                    $nsdl_orderid = isset($response['nsdl_orderid']) && !empty($response['nsdl_orderid']) ? $response['nsdl_orderid'] : $nsdlOrderID;
                                    $name = isset($response['name']) && !empty($response['name']) ? $response['name'] : 'NA';
                              
                                    $printDataJson = json_encode($printData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                    $printDataUtf8 = mb_convert_encoding($printDataJson, 'UTF-8', 'UTF-8');
                                    $encodedData = base64_encode($printDataUtf8);
                               
                                    $insData = [
                                        'order_id'      => $nsdl_orderid,
                                        'username'      => $user_data['username'],
                                        'name'          => $name,
                                        'idNumber'      => $phone,
                                        'service'       => "NSDL_PAN",
                                        'date_time'     => current_timestamp(),
                                        'printData'     => $encodedData,
                                        'status'       =>  "Pending",
                                        'photo'         => "",
                                    ];

                                    $insertIddata = db_insert("printRecords", $insData);
    
                                    if ($insertIddata) {
                                      $fields = [
                                          'name'               => 'Name',
                                          'phone'              => 'Mobile',
                                          'nsdl_orderid'       => 'OrderId',
                                          'branchCode'         => 'BranchCode',
                                          'applicationTypefull'=> 'Application',
                                          'redirectUrl'        => 'Link to Process',
                                      ];

                                      $whamessage = "Dear {$user_data['name']},\nYour Request for Number *{$phoneNumber}* To NSDL {$response['applicationTypefull']} has been Process Please click Link to complete your Application.\n\n";
                                      foreach ($fields as $key => $label) {
                                          if (!empty($response[$key]) && isset($response[$key])) {
                                              $whamessage .= "*$label*: {$response[$key]}\n";
                                          }
                                      }
                                      $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
                                      send_sms($user_data['mobile'], $whamessage);
                                     if(isset($response['redirectUrl']) && !empty($response['redirectUrl'])){
                                       awal_alert_msg("Redirecting... please dont go back or Refrsh.", 'warning');
                                      redirect(''.$response['redirectUrl'].'', 3000);
                                      }else{
                                          awal_alert_msg("NSDL Redirect Link Not Generated Please check PrintRecord!", 'error');
                                      }
                                    } else {
                                        awal_alert_msg("Print Record Insert Server Error!", 'error');
                                    }
                                  } else {
                                      awal_alert_msg("Report 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 {
                      awal_alert_msg("Insufficient Wallet Balance!", 'error');
                  }
              } else {
                  awal_alert_msg("Please Fill All Valid Details!", 'error');
              }
          }
          
// If NSDL Website redirected back with its encrypted response
if (isset($_GET['encrypted_data'])) {

    $__E = urldecode($_GET['encrypted_data']);
    $__E = str_replace(' ', '+', $__E);
    $__E = trim($__E);
    $request = [
        'encrypted_data' => $__E,
    ];
    
    $responseApi = NSDL_pan_encription_Status_api_run($request);
    $response = json_decode($responseApi, true);
    if (!is_array($response)) {
        awal_alert_msg('Invalid response from NSDL status API', 'error');
        return;
    }

    $status        = (string)($response['status'] ?? '');
    $statusMessage = (string)($response['statusMessage'] ?? '');
    $nsdl_orderid  = (string)($response['nsdl_orderid'] ?? '');
    $acknowledgeNo = (string)($response['acknowledgeNo'] ?? '');
    $orderid       = (string)($response['orderid'] ?? '');

    if ($status === '100') {
        // if ($nsdl_orderid === '') {
        //     awal_alert_msg('NSDL success but order id missing. Please contact support.', 'error');
        //     return;
        // }
        $pan_info = db_fetch_array('reports', "order_id = '{$nsdl_orderid}'");

        if (!empty($pan_info) && !empty($pan_info['order_id'])) {

            $holderName = (string)($pan_info['name'] ?? '');
            $order_idt  = (string)($pan_info['order_id'] ?? '');

            $echoPayload = [
                'acknowledgeNo'  => $acknowledgeNo,
                'orderid'        => $orderid,
                'nsdl_orderid'   => $nsdl_orderid ?: 'NA',
                'encrypted_data' => $__E,   
                'username'       => $user_data['username'] ?? '',
            ];
            $echoJson   = json_encode($echoPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            $echoUtf8   = mb_convert_encoding($echoJson, 'UTF-8', 'UTF-8');
            $encoded    = base64_encode($echoUtf8);

            $reportUpdate = [
                'date_time'        => current_timestamp(),
                'api_response'     => $encoded,
                'status'           => ucwords($response['statusMessage']),
            ];
            $okReport = db_update('reports', $reportUpdate, "order_id = '{$nsdl_orderid}'");

            $printdataupdate = [
                'date_time'    => current_timestamp(),
                'status'       => ucwords($response['statusMessage']),
            ];
            $okMember = db_update('printRecords', $printdataupdate, "order_id = '{$nsdl_orderid}'");

            if ($okReport) {
                awal_alert_msg("NSDL updated successfully for Order: {$nsdl_orderid}", 'success');
                redirect('Pan_Apply_Correction', 3000);
            } else {
                awal_alert_msg('NSDL updated, but failed to write report row.', 'warning');
            }

        } else {
            awal_alert_msg('No matching order found in our database!', 'error');
            redirect('Pan_Apply_Correction', 3000);
        }

    } else {
        $err = $response['error'] ?? $statusMessage ?: 'Server Down';
        awal_alert_msg($err, 'error');
        redirect('Pan_Apply_Correction', 3000);
    }
}

          ?>
          
           <div class="col-sm-12 mb-2">
            <div class="d-flex align-items-center justify-content-between alert alert-info">
              <div>
                <strong>Your Branch ID:</strong>
                <span class="text-monospace"><?= htmlspecialchars($user_data['psa_id'] ?? '') ?></span>
              </div>
              <form method="post" 
                    onsubmit="return confirm('This will replace your current Branch ID for future PAN operations.\nProceed to regenerate?');">
                <button type="submit" name="generate_psa" class="btn btn-sm btn-outline-danger">
                  <i class="fas fa-sync-alt"></i> Regenerate
                </button>
              </form>
            </div>
          </div>
          <form action="" method="POST" class="row">
            <div class="col-sm-6 mb-3">
              <label>Name</label>
              <div class="input-group">
                <input type="text" name="name" class="form-control" placeholder="Enter Full Name" minlength="4" maxlength="80" required>
              </div>
            </div>
            <div class="col-sm-6 mb-3">
              <label for="gender" class="form-label">Select Gender:</label>
                  <select autofocus class="form-control" name="gender" id="gender" required>
                     <option value="M">Male</option>
                     <option value="F">Female</option>
                     <option value="T">Transgender</option>
                  </select>
            </div>
            <div class="col-sm-6 mb-3">
              <label>Mobile Number</label>
              <input type="number" name="phoneNumber" placeholder="Enter Mobile Number" maxlength="10" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==10) return false;" required>
            </div>
            <div class="col-sm-6 mb-3">
              <label>Email ID</label>
              <input type="email" name="emailID" placeholder="abc@gmail.com" minlength="15" maxlength="100" class="form-control" required>
            </div>
            <div class="col-sm-6 mb-3">
              <label for="applicationMode" class="form-label">Application Mode:</label>
                  <select autofocus class="form-control" name="applicationMode" id="applicationMode" required>
                     <option selected value="EKYC">EKYC</option>
                     <option value="ESIGN">ESIGN</option>
                  </select>
            </div>
            <div class="col-sm-6 mb-3">
              <label for="applicationType" class="form-label">Application Type:</label>
              <select name="applicationType" id="applicationType" class="form-control" required>
              </select>
            </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> <?= $user_data['pan_apply_fee']; ?>
              </button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

<script>
  document.addEventListener("DOMContentLoaded", function () {
    const operators = [
      { code: "49A",  name: "PAN - Indian Citizen (Form 49A)" },
      { code: "CR",   name: "Changes or Correction in existing PAN" },
    ];
    const stateSelect = document.getElementById("applicationType");
    operators.forEach(op => {
      const option = document.createElement("option");
      option.value = op.code;
      option.textContent = op.name;
      stateSelect.appendChild(option);
    });
  });
</script>
<?php
} else {
   require_once("404.php");
}
} else {
   awal_alert_msg('You Do Not Have Any NSDL Pan Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>