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

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

$response = null;
$frontSrc = null;
$backSrc  = null;
$pdfSrc   = null;
$tokenFileName = null;
?>

<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'])) {

    $type     = trim($_POST['type']);
    $password = trim($_POST['password']);
    $mobile   = trim($_POST['mobile'] ?? "");

    if (!empty($type) && !empty($password) && isset($_FILES['file']) && $_FILES['file']['error'] == 0) {

        $fileTmp  = $_FILES['file']['tmp_name'];
        $fileName = $_FILES['file']['name'];
        $fileExt  = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if ($fileExt !== "pdf") {
            awal_alert_msg("Only PDF file allowed!", "error");
        } else {

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

            if ($old_balance >= $amount) {

                $order_id = order_txn_id();
                $tokenFileName = "Aadhaar_Convert_" . $order_id;

                $responseApi = aadhaar_pdf_convert_api($fileTmp, $fileName, $type, $password, $mobile);
                $response = json_decode($responseApi, true);

                if (isset($response['status']) && $response['status'] == true) {

                    $frontSrc = $response['front'] ?? null;
                    $backSrc  = $response['back'] ?? null;
                    $pdfSrc   = $response['pdf'] ?? null;

                    if (!empty($frontSrc) && strpos($frontSrc, "data:image") !== 0) {
                        $frontSrc = "data:image/png;base64," . $frontSrc;
                    }

                    if (!empty($backSrc) && strpos($backSrc, "data:image") !== 0) {
                        $backSrc = "data:image/png;base64," . $backSrc;
                    }

                    if (!empty($pdfSrc) && strpos($pdfSrc, "data:application/pdf;base64,") !== 0) {
                        $pdfSrc = "data:application/pdf;base64," . $pdfSrc;
                    }

                    $updateSuccess = db_update(
                        "members",
                        ["balance" => $new_balance],
                        "user_id='{$user_data['user_id']}'"
                    );

                    if ($updateSuccess) {

                        db_insert("reports", [
                            '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'        => "Aadhaar_PDF_Convert",
                            'type'           => "Debit",
                            'account_number' => $mobile,
                            'app_type'       => "Aadhaar_PDF_Convert",
                            'amount'         => $amount,
                            'main_amount'    => $amount,
                            'old_balance'    => $old_balance,
                            'new_balance'    => $new_balance,
                            'txn_id'         => $order_id,
                            'ref_id'         => $order_id,
                            'description'    => "Rs.{$amount} Debited for Aadhaar PDF Convert",
                            'date_time'      => current_timestamp(),
                            'status'         => "Success"
                        ]);

                        awal_alert_msg("Aadhaar PDF Converted Successfully", "success");

                    } else {
                        awal_alert_msg("Wallet debit failed. Contact support.", "error");
                    }

                } else {
                    awal_alert_msg($response['error'] ?? $response['error'] ?? "API Error", "error");
                }
            } else {
                awal_alert_msg("Insufficient Wallet Balance!", "error");
            }
        }

    } else {
        awal_alert_msg("Please fill all required details!", "error");
    }
}
?>

<form action="" method="POST" enctype="multipart/form-data" class="row">

  <div class="col-md-12 mb-3">
    <label>Upload Aadhaar PDF</label>
    <input type="file" name="file" accept="application/pdf" class="form-control" required>
  </div>

  <div class="col-md-12 mb-3">
    <label>Select Type</label>
    <select name="type" class="form-control" required>
      <option value="">Select Type</option>
      <option value="Yellow">Yellow</option>
      <option value="White">White</option>
    </select>
  </div>

  <div class="col-md-12 mb-3">
    <label>Password</label>
    <input type="text" name="password" placeholder="Enter PDF Password" class="form-control" required>
  </div>

  <div class="col-md-12 mb-3">
    <label>Mobile Optional</label>
    <input type="text"
           name="mobile"
           placeholder="Enter Mobile Number"
           maxlength="10"
           class="form-control"
           oninput="this.value=this.value.replace(/[^0-9]/g,'');">
  </div>

  <div class="col-md-12 mb-3 d-flex justify-content-between">
    <button type="button" class="btn btn-secondary">
      ₹ <?= $user_data['aadhaarPvc_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 (!empty($frontSrc) || !empty($backSrc) || !empty($pdfSrc)) { ?>
  <div class="col-md-8 mb-2">

    <div class="row">
      <?php if (!empty($frontSrc)) { ?>
      <div class="col-md-6 mb-3">
        <div class="card h-100">
          <div class="card-header bg-success text-white">
            Front Preview
            <a href="<?= $frontSrc ?>"
               download="<?= $tokenFileName ?>_Front.png"
               class="btn btn-warning btn-sm float-right text-dark">
              <i class="fas fa-download"></i> Download
            </a>
          </div>
          <div class="card-body text-center">
            <img src="<?= $frontSrc ?>" class="img-fluid border rounded" style="max-height:350px;">
          </div>
        </div>
      </div>
      <?php } ?>

      <?php if (!empty($backSrc)) { ?>
      <div class="col-md-6 mb-3">
        <div class="card h-100">
          <div class="card-header bg-info text-white">
            Back Preview
            <a href="<?= $backSrc ?>"
               download="<?= $tokenFileName ?>_Back.png"
               class="btn btn-warning btn-sm float-right text-dark">
              <i class="fas fa-download"></i> Download
            </a>
          </div>
          <div class="card-body text-center">
            <img src="<?= $backSrc ?>" class="img-fluid border rounded" style="max-height:350px;">
          </div>
        </div>
      </div>
      <?php } ?>
    </div>

    <?php if (!empty($pdfSrc)) { ?>
    <div class="card mb-3">
      <div class="card-header bg-dark text-white">
        PDF Preview
        <a href="<?= $pdfSrc ?>"
           download="<?= $tokenFileName ?>.pdf"
           class="btn btn-warning btn-sm float-right text-dark">
          <i class="fas fa-download"></i> Download PDF
        </a>
      </div>
      <div class="card-body p-0">
        <iframe src="<?= $pdfSrc ?>" width="100%" height="650px" style="border:none;"></iframe>
      </div>
    </div>
    <?php } ?>

  </div>
<?php } ?>

</div>

<?php
} else {
    require_once("404.php");
}
} else {
    awal_alert_msg('You Do Not Have Any Farmer Service Active!', 'info', 'dashboard');
}

require_once("../layouts/members/foot.php");
?>
```
