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

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

$response = null;
$pdfSrc = null;
$typeSelected = 'OLD'; // default type

?>
<div class="row">

<!-- LEFT SIDE: FORM -->
<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'])) {

    $vehicalNumber = strtoupper(trim($_POST['vehicalNumber']));
    $fatherName    = strtoupper(trim($_POST['fatherName'] ?? ''));
    $typeSelected  = strtoupper($_POST['type'] ?? 'OLD');

    if (!empty($vehicalNumber) && !empty($typeSelected)) {

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

        if ($old_balance >= $amount) {

            $order_id = order_txn_id();

            $request = [
                'vehicalNumber' => $vehicalNumber,
                'type'          => $typeSelected, // NEW or OLD
                'fatherName'    => $fatherName,
                'order_id'      => $order_id,
            ];

            // Use your existing API function
            $responseApi = vehicalRcVerificationPdf_run($request);
            $response    = json_decode($responseApi, true);

            if (isset($response['statusCode']) && $response['statusCode'] == '200') {

                $pdfSrc = $response['pdf'] ?? null;

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

                if ($updateSuccess) {

                    // Reports entry
                    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'       => "VEHICALRCPDF",
                        'type'          => "Debit",
                        'account_number'=> $response['is_number'] ?? $vehicalNumber,
                        'app_type'      => "VEHICALRCPDF",
                        'amount'        => $amount,
                        'main_amount'   => $amount,
                        'old_balance'   => $old_balance,
                        'new_balance'   => $new_balance,
                        'txn_id'        => $order_id,
                        'ref_id'        => $response['is_number'] ?? $vehicalNumber,
                        'description'   => "Rs.{$amount} Debited for Vehicle RC PDF",
                        'date_time'     => current_timestamp(),
                        'status'        => "Success"
                    ]);

                    // SMS
                    $whamessage = "Dear {$user_data['name']},\nYour Vehicle RC request for {$vehicalNumber} is completed.\n\nName: {$response['name']}\nFather: {$response['fathername']}\nAddress: {$response['address']}\n\nRegards,\n{$site_data['brand']}";
                    send_sms($user_data['mobile'], $whamessage);

                    awal_alert_msg("Vehicle RC PDF Generated Successfully", "success");

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

            } else {
                awal_alert_msg($response['message'] ?? 'API Error', 'error');
            }

        } else {
            awal_alert_msg("Insufficient Wallet Balance!", 'error');
        }

    } else {
        awal_alert_msg("Please Fill All Valid Details!", 'error');
    }
}
?>

<form action="" method="POST" class="row">
  <div class="col-md-12 mb-3">
    <label>Vehicle Number</label>
    <input type="text" name="vehicalNumber" maxlength="15" placeholder="Enter Vehicle Number"
           oninput="this.value=this.value.toUpperCase().replace(/\s+/g,'');"
           class="form-control" required>
  </div>

  <div class="col-md-12 mb-3">
    <label>Father/Husband Name <span style="color:red;">(Optional)</span></label>
    <input type="text" name="fatherName" maxlength="55" placeholder="Enter Father/Husband Name" class="form-control">
  </div>

  <div class="col-md-12 mb-3">
    <label>Card Type</label>
    <select name="type" class="form-control" required>
      <option value="OLD" <?= ($typeSelected == 'OLD') ? 'selected' : '' ?>>Without Chip</option>
      <option value="NEW" <?= ($typeSelected == 'NEW') ? 'selected' : '' ?>>With Chip</option>
    </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['vehical_rc_fee'] ?></button>
    <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
  </div>
</form>
    </div>
  </div>
</div>

<!-- RIGHT SIDE: PDF PREVIEW -->
<?php if ($pdfSrc) { ?>
<div class="col-md-8 mb-2">
  <div class="card">
    <div class="card-header bg-success text-white">
      Vehicle RC PDF Preview
      <a href="<?= $pdfSrc ?>" download="Vehicle_RC.pdf" class="btn btn-warning btn-sm float-right text-dark">
        <i class="fas fa-download"></i> Download
      </a>
    </div>
    <div class="card-body p-0">
      <iframe src="<?= $pdfSrc ?>" width="100%" height="600px" style="border:none;"></iframe>
    </div>
  </div>
</div>
<?php } ?>

</div>

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