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

$response = [];
$panNumber = '';

if ($user_data['pan2uid_find_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
        if (isset($_POST['submit'])) {

            $panNumber = strtoupper(trim($_POST['panNumber'] ?? ''));

            if (!empty($panNumber) && preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/', $panNumber)) {

                $amount = $user_data['pan2uid_find_fee'];
                $old_balance = $user_data['balance'];
                $new_balance = $old_balance - $amount;

                if ($old_balance >= $amount) {

                    $order_id = order_txn_id();

                    $request = [
                        'panNumber' => $panNumber,
                        'order_id'  => $order_id
                    ];

                    $apiResponse = pantoUidfind_run($request);
                    $response = json_decode($apiResponse, true);

                    if (!is_array($response)) {
                        $response = [];
                    }

                    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'        => "PAN UID FIND REQUEST",
                                'type'           => "Debit",
                                'account_number' => $panNumber,
                                'app_type'       => "PAN UID FIND REQUEST",
                                'amount'         => $amount,
                                'main_amount'    => $amount,
                                'old_balance'    => $old_balance,
                                'new_balance'    => $new_balance,
                                'txn_id'         => $order_id,
                                'ref_id'         => $response['aadhar'] ?? $panNumber,
                                'description'    => "Rs.{$amount} Has Been Debit From Wallet for PAN UID FIND {$panNumber}",
                                'date_time'      => current_timestamp(),
                                'status'         => "Success"
                            ];

                            $insertId = db_insert("reports", $insData);

                            if ($insertId) {

                                $fields = [
                                    'name'      => 'Name',
                                    'dob'       => 'DOB',
                                    'gender'    => 'Gender',
                                    'aadhar'    => 'Aadhaar No',
                                    'panNumber' => 'PAN No',
                                ];

                                $whamessage = "Dear {$user_data['name']},\nYour Request for PAN *{$panNumber}* UID Find has been Complete.\n\n";

                                foreach ($fields as $key => $label) {
                                    if (isset($response[$key]) && !empty($response[$key])) {
                                        $whamessage .= "*$label*: {$response[$key]}\n";
                                    }
                                }

                                $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";

                                send_sms($user_data['mobile'], $whamessage);

                            } 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 {
                    awal_alert_msg("Insufficient Wallet Balance!", 'error');
                }

            } else {
                awal_alert_msg("Please Enter Valid PAN Number!", 'error');
            }
        }
        ?>

        <form action="" method="POST" class="row">
          <div class="col-md-12 mb-3">
            <label>PAN Number</label>
            <input type="text"
                   name="panNumber"
                   id="panNumber"
                   placeholder="Enter PAN Number"
                   maxlength="10"
                   class="form-control"
                   oninput="this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');"
                   required>
            <small id="panError" class="text-danger" style="display:none;">
              Invalid PAN Number. Format: ABCDE1234F
            </small>
          </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['pan2uid_find_fee']; ?>
            </button>

            <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">
              Submit
            </button>
          </div>
        </form>

      </div>
    </div>
  </div>

  <?php if (isset($response['status']) && $response['status'] == '100') { ?>
  <div class="col-md-8 mb-2">
    <div class="card text-danger">
      <div class="card-header bg-danger text-white py-2">
        <span class="mr-auto">Details Searching Complete PAN No: <strong><?= htmlspecialchars($panNumber); ?></strong></span>
      </div>

      <div class="table-responsive">
        <table class="table table-bordered table-striped">
          <tbody>

            <?php if (!empty($response['name'])) { ?>
            <tr>
              <td><strong>Name</strong></td>
              <td><?= htmlspecialchars($response['name']); ?></td>
            </tr>
            <?php } ?>

            <?php if (!empty($response['dob'])) { ?>
            <tr>
              <td><strong>DOB</strong></td>
              <td><?= htmlspecialchars($response['dob']); ?></td>
            </tr>
            <?php } ?>

            <?php if (!empty($response['gender'])) { ?>
            <tr>
              <td><strong>Gender</strong></td>
              <td><?= htmlspecialchars($response['gender']); ?></td>
            </tr>
            <?php } ?>

            <?php if (!empty($response['aadhar'])) { ?>
            <tr>
              <td><strong>Aadhaar Number</strong></td>
              <td><?= htmlspecialchars($response['aadhar']); ?></td>
            </tr>
            <?php } ?>

            <?php if (!empty($response['panNumber'])) { ?>
            <tr>
              <td><strong>PAN Number</strong></td>
              <td><?= htmlspecialchars($response['panNumber']); ?></td>
            </tr>
            <?php } ?>

          </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php } ?>

</div>

<script>
document.getElementById('panNumber').addEventListener('input', function () {
    let pan = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
    this.value = pan;

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

    if (pan.length === 0 || regex.test(pan)) {
        err.style.display = 'none';
        this.classList.remove('is-invalid');
        if (regex.test(pan)) {
            this.classList.add('is-valid');
        } else {
            this.classList.remove('is-valid');
        }
    } else {
        err.style.display = 'block';
        this.classList.add('is-invalid');
        this.classList.remove('is-valid');
    }
});
</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");
?>