<?php
require_once("../layouts/members/head.php");
if ($user_data['electricBill_services'] == "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
          $fetchOperatoer = ElectricBill_fetch_AllIndia_Opertor_Fetach_run();
          $OperatorResponse = json_decode($fetchOperatoer, true) ?? '';
          
          $apiResponseData = null;
          if (isset($_POST['submit'])) {
              $caNumber = $_POST['caNumber'] ?? '';
              $operator = $_POST['operator'] ?? '';

              if (!empty($caNumber) && (!empty($operator))) {
                  $amount = $user_data['electricBill_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($old_balance >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'caNumber' => $caNumber,
                          'operator' => $operator,
                      ];

                      $responseApi = ElectricBill_fetch_AllIndia_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'      => $order_id,
                                  'service'       => "ElectricBill_Details",
                                  'type'          => "Debit",
                                  'account_number'=> $response['caNumber'],
                                  'app_type'      => "ElectricBill_Details",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['caNumber'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for ElectricBill_Details Name {$response['name']} CA No ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  $fields = [
                                      'caNumber' => 'CA No',
                                      'name' => 'Name',
                                      'billAmount' => 'Bill Amount',
                                      'totalAmount' => 'Total Amount',
                                      'dueDate' => 'Due Date',
                                      'billGeneratedDate' => 'Bill Generated Date',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for CA Number *{$caNumber}* To Electric Bill Verification has been Complete.\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);
                              } 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 Fill All Valid Details!", 'error');
              }
          }
          ?>
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
            <label for="operator" class="form-label">Select Operator</label>
            <select name="operator" id="operator" class="form-control select2" required>
                <option value="">-- Select Operator --</option>
                <?php
                if ($OperatorResponse['status'] == 'success') {
                    foreach ($OperatorResponse['operators'] as $op) {
                         echo "<option value='" . $op['op'] . "' data-opid='" . $op['op'] . "'>" . $op['name'] . "</option>";
                    }
                }
                ?>
            </select>
            </div>
            <div class="col-md-12 mb-3">
              <label>CA Number</label>
              <input type="number" name="caNumber" placeholder="Enter CA Number" maxlength="20" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==20) return false;"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['electricBill_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 CA No: <strong><?= $caNumber ?? 'N/A'; ?></strong></span>
      
           <button class="btn btn-primary" onclick="printBill()">Print</button>
    </div>
    <div class="table-responsive" id="printSection">
      <table class="table table-bordered table-striped">
        <tbody>
          <?php if (!empty($response['caNumber'])): ?>
          <tr>
            <td><strong>CA Number</strong></td>
            <td><?= htmlspecialchars($response['caNumber']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['name'])): ?>
          <tr>
            <td><strong>Name</strong></td>
            <td><?= htmlspecialchars($response['name']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['totalAmount'])): ?>
          <tr>
            <td><strong>Total Amount</strong></td>
            <td><?= htmlspecialchars($response['totalAmount']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['billAmount'])): ?>
          <tr>
            <td><strong>Bill Amount</strong></td>
            <td><?= htmlspecialchars($response['billAmount']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['dueDate'])): ?>
          <tr>
            <td><strong>Due Date</strong></td>
            <td><?= htmlspecialchars($response['dueDate']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['billGeneratedDate'])): ?>
          <tr>
            <td><strong>Bill Generated Date</strong></td>
            <td><?= htmlspecialchars($response['billGeneratedDate']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['billPeriod'])): ?>
          <tr>
            <td><strong>Bill Period</strong></td>
            <td><?= htmlspecialchars($response['billPeriod']); ?></td>
          </tr>
          <?php endif; ?>
          
        </tbody>
      </table>
    </div>
  </div>
</div>

    <?php } ?>
  <script>
function printBill() {
    var content = document.getElementById("printSection").innerHTML;

    var printWindow = window.open('', '_blank', 'width=800,height=600');
    printWindow.document.write(`
        <html>
            <head>
                <title>Electricity Bill</title>
                <style>
                    body { font-family: Arial, sans-serif; padding: 20px; }
                    table { width: 100%; border-collapse: collapse; }
                    th, td { border: 1px solid #000; padding: 8px; text-align: left; }
                    th { background-color: #f2f2f2; }
                    h5 { margin-bottom: 20px; }
                </style>
            </head>
            <body>
                ${content}
                <script>
                    window.onload = function() {
                        window.print();
                    };
                <\/script>
            </body>
        </html>
    `);
    printWindow.document.close();
}
</script>  
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <!-- Init Select2 -->
<script>
$(document).ready(function () {
    $('#operator').on('change', function () {
        var selectedOpId = $(this).find(':selected').data('opid');
        $('#opid').val(selectedOpId);
    });
    $('#operator').select2({
        placeholder: "-- Select Operator --",
        allowClear: true,
        width: '100%'
    });
});
</script>
</div>
<?php
} else {
    require_once("404.php");
}
} else {
    awal_alert_msg('You Do Not Have Any Electric Service Active!', 'info', 'dashboard');
}

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