<?php
require_once("../layouts/members/head.php");

if ($user_data['sharmadhan_service'] === "YES") {
  if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
?>

<div class="row">
  <div class="col-md-4 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
        $response = [];
        if (isset($_POST['submit'])) {
          $registration_no = strtoupper(trim($_POST['registration_no']));
          if (!empty($registration_no)) {
            $amount = $user_data['sharmadhan_fee'];
            $old_balance = $user_data['balance'];
            $new_balance = $old_balance - $amount;

            if ($user_data['balance'] >= $amount) {
              $order_id = order_txn_id();

              // Call the API function and decode the JSON response
              $request = ['registration_no' => $registration_no];
              $api_response_raw = sharmadhad_card_detilas_api_run($request);
              $api_json = json_decode($api_response_raw, true);

              if (!empty($api_json) && is_array($api_json)) {
                if ($api_json['status'] === "100") {
                  $data = $api_json['data'];

                  // Update balance in DB
                  $updateSuccess = db_update("members", ["balance" => $new_balance], " user_id='" . $user_data['user_id'] . "' ");
                  if ($updateSuccess) {
                    $log = [
                      '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' => "Shramadhan_Verification",
                      'type' => "Debit",
                      'account_number' => $registration_no,
                      'app_type' => "Shramadhan_Verification",
                      'amount' => $amount,
                      'main_amount' => $amount,
                      'old_balance' => $old_balance,
                      'new_balance' => $new_balance,
                      'txn_id' => $order_id,
                      'ref_id' => $registration_no,
                      'description' => "Rs.{$amount} debited for Shramadhan Card Verification {$registration_no}",
                      'date_time' => current_timestamp(),
                      'status' => "Success"
                    ];
                    db_insert("reports", $log);

                    // Send notification SMS
                    $whamessage = "Dear {$user_data['name']},\nYour Shramadhan Card verification completed.\n\n*Registration No.*: {$registration_no}\n*Aadhaar No*: {$data['mobile_verified']}\n*Name*: {$data['name_en']}\n*DOB*: {$data['dob_en']}\n\n_*{$site_data['brand']}*_";
                    send_sms($user_data['mobile'], $whamessage);

                    $response = $data;
                    awal_alert_msg("Verification Successful", 'success');
                  } else {
                    awal_alert_msg("Balance deducted but DB update failed.", 'error');
                  }
                } else {
                  $errorMessage = $api_json['message'] ?? $api_json['error'] ?? 'Unknown API error.';
                  awal_alert_msg($errorMessage, 'error');
                }
              } else {
                awal_alert_msg("Invalid or empty response from Shramadhan API.", 'error');
              }
            } else {
              awal_alert_msg("Insufficient Wallet Balance!", 'error');
            }
          } else {
            awal_alert_msg("Please enter a valid Registration Number", 'error');
          }
        }
        ?>

        <form method="POST" class="row">
          <div class="col-md-12 mb-3">
            <label>Registration Number<sup style="color:blue; font-weight:bold;"> &nbsp;&nbsp;Jharkhand Sharmadhan Lobour Card Details & Aadhaar Number Find</sup></label>
            <input type="text" name="registration_no" placeholder="Enter Registration Number" maxlength="30" class="form-control" 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> <?= $user_data['sharmadhan_fee']; ?></button>
            <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Proceed with verification?');">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <?php if (!empty($response)) { ?>
 <div class="col-md-8 mb-2">
  <div class="card">
    <div class="card-header bg-danger text-white d-flex justify-content-between align-items-center">
      <span>Verification Result - Reg. No: <strong><?= htmlspecialchars($response['registration_no']); ?></strong></span>
      <button class="btn btn-primary btn-sm" onclick="printDiv('print-section')">
  <i class="fas fa-print"></i> Print
</button>

    </div>
    <div id="print-section" class="table-responsive p-3">
      <table class="table table-bordered table-striped">
        <tbody>
          <tr><td><strong>Aadhaar No</strong></td><td><?= $response['mobile_verified']; ?> </td></tr>
           <tr><td><strong>Name</strong></td><td><?= $response['name_en']; ?> / <?= $response['name_hi']; ?></td></tr>
          <tr><td><strong>Guardian</strong></td><td><?= $response['guardian_en']; ?> / <?= $response['guardian_hi']; ?></td></tr>
          <tr><td><strong>Date of Birth</strong></td><td><?= $response['dob_en']; ?> / <?= $response['dob_hi']; ?></td></tr>
          <tr><td><strong>Gender</strong></td><td><?= $response['gender_en']; ?> / <?= $response['gender_hi']; ?></td></tr>
          <tr><td><strong>Address</strong></td><td><?= nl2br($response['address_en']); ?><hr><?= nl2br($response['address_hi']); ?></td></tr>
          <tr><td><strong>Issuing Authority</strong></td><td><?= $response['issuing_authority']; ?></td></tr>
          <tr><td><strong>Issue Date</strong></td><td><?= $response['issue_date']; ?></td></tr>
         <tr>
  <td><strong>Card Details</strong></td>
  <td>
    <div style="font-family: monospace; white-space: pre-wrap; background: #f8f9fa; padding:10px; border-radius:5px;">
      <?= htmlspecialchars($response['card_details']); ?>
    </div>
  </td>
</tr>
<?php if (!empty($response['photo_base64'])): ?>
<tr>
  <td><strong>Photo</strong></td>
  <td><img src="<?= $response['photo_base64']; ?>" alt="Photo" style="max-width:200px;height:auto;"></td>
</tr>
<?php endif; ?>
<?php if (!empty($response['qr_image_base64'])): ?>
<tr>
  <td><strong>QR Code</strong></td>
  <td><img src="<?= $response['qr_image_base64']; ?>" alt="QR" style="max-width:200px;height:auto;"></td>
</tr>


          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

  <?php } ?>
</div>
<script>
function printDiv(divId) {
  var printContents = document.getElementById(divId).innerHTML;
  var originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;
  window.print();
  document.body.innerHTML = originalContents;
  
}
</script>

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