<?php
require_once("../layouts/members/head.php");
if ($user_data['mobile_dth_recharge_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
          $apiResponseData = null;
          if (isset($_POST['submit'])) {
              $phoneNumber = $_POST['phoneNumber'] ?? '';
              $readAmount  = $_POST['readAmount'] ?? '';
              $operatorName= $_POST['operatorName'] ?? '';

              if (!empty($phoneNumber) && !empty($readAmount) && !empty($operatorName)) {
                 if (!is_numeric($readAmount)) {
                     awal_alert_msg("Amount must be a number.", 'error');
                 }elseif (is_numeric($readAmount) && $readAmount >= 10 && $readAmount <= 5000) {
                  $amount = $readAmount;
                  $old_balance = $user_data['balance'];

                  if ($old_balance >= $amount) {
                      $request = [
                          'number' => $phoneNumber,
                          'amount' => $readAmount,
                          'opcode' => $operatorName,
                      ];

                      $operator_info = db_fetch_array("operators", "operator_code = '{$operatorName}'");
                      $old_operator_name   = $operator_info['operator_name'] ?? '';
                      $commissionPercent   = $operator_info['plan_operator_id'] ?? '';
                      
                       if (!is_numeric($commissionPercent)) {
                           awal_alert_msg("Commission Amount must be a number.", 'error');
                       }elseif (is_numeric($commissionPercent) && $commissionPercent <= 5) {
                           
                      $deductAmount = $amount - (($amount * $commissionPercent) / 100);
                      $new_balance = $old_balance - $deductAmount;
                          
                      $responseApi = Quick_Recharge_api_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'      => $response['orderid'],
                                  'service'       => "RECHARGE",
                                  'type'          => "Debit",
                                  'account_number'=> $response['number'],
                                  'app_type'      => $old_operator_name." Recharge",
                                  'amount'        => $deductAmount,
                                  'main_amount'   => $deductAmount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $response['orderid'],
                                  'ref_id'        => $response['number'],
                                  'description'   => "Rs.{$deductAmount} Has Been Debit From Wallet for {$old_operator_name} Recharge {$response['provider']} Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => ucwords($response['statusMessage'])
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                  
                            //   $printData = array(
                            //       'number'  => isset($response['number']) && !empty($response['number']) ? $response['number'] : $phoneNumber,
                            //       'operator'=> $old_operator_name ?? 'NA',
                            //       'orderid' => isset($response['orderid']) && !empty($response['orderid']) ? $response['orderid'] : 'NA',
                            //       'opid'    => isset($response['opid']) && !empty($response['opid']) ? $response['opid'] : '',
                            //       'message' => isset($response['message']) && !empty($response['message']) ? $response['message'] : '',
                            //       'username'      => $user_data['username'],
                            //   );
                            //   $number   = isset($response['number']) && !empty($response['number']) ? $response['number'] : $phoneNumber;
                            //   $order_id = isset($response['orderid']) && !empty($response['orderid']) ? $response['orderid'] : '';
                              
                            //   $printDataJson = json_encode($printData, JSON_UNESCAPED_UNICODE);
                            //   $printDataUtf8 = mb_convert_encoding($printDataJson, 'UTF-8', 'UTF-8');
                            //   $encodedData = base64_encode($printDataUtf8);
                               
                            //   $insData = [
                            //       'order_id'      => $order_id,
                            //       'username'      => $user_data['username'],
                            //       'name'          => $old_operator_name,
                            //       'idNumber'      => $number,
                            //       'service'       => "Recharge",
                            //       'date_time'     => current_timestamp(),
                            //       'printData'     => $encodedData,
                            //       'status'       =>  ucwords($response['statusMessage']),
                            //       'photo'         => "",
                            //   ];

                            //   $insertIddata = db_insert("printRecords", $insData);
    
                            //   if ($insertIddata) {
                                  $fields = [
                                      'number'   => 'Number',
                                      'amount'   => 'Amount',
                                      'orderid'  => 'OrderId',
                                      'message'  => 'message',
                                  ];

                                  $whamessage = "Dear {$user_data['name']},\nYour Request for Number *{$phoneNumber}* To Recharge 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("Print Record Insert Server Error!", 'error');
                            //   }
                            } else {
                                awal_alert_msg("Report 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("Commission amount not more than 5 !", 'error');
                    }
                  } else {
                      awal_alert_msg("Insufficient Wallet Balance!", 'error');
                  }
                } else {
                    awal_alert_msg("Amount cannot be less than 10 or more than 5000.", '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>Mobile/DTH Number</label>
              <div class="input-group">
                <input id="mobileInput" type="tel" name="phoneNumber" class="form-control" placeholder="Enter Mobile/DTH Number" minlength="5" maxlength="25" required>
                <div class="input-group-append">
                  <button id="fetchPlansBtn" type="button" class="btn btn-info" disabled>
                    <i class="fas fa-search"></i> Plans
                  </button>
                </div>
              </div>
              <small class="text-muted">Fetch works when exactly <b>10 digits</b> are entered.</small>
              <div id="plansError" class="text-danger mt-1" style="display:none;"></div>
            </div>
            <div class="col-md-12 mb-3">
              <label for="operatorName" class="form-label">Select Operator:</label>
              <select name="operatorName" id="operatorName" class="form-control" required>
                <option value="">Select Operator</option>
              </select>
            </div>
            <div class="col-md-12 mb-3">
              <label>Amount</label>
              <input type="number" name="readAmount" placeholder="Enter amount" maxlength="4"  class="form-control" required>
            </div>
            <div class="col-md-12 mb-3 d-flex justify-content-between">
              <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#showDetailsModal">Commission</button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- RIGHT: Plans table -->
    <div class="col-md-8 mb-2">
      <div class="card">
        <div class="card-header bg-info text-white py-2">
          <span class="mr-auto">Available Plans</span>
        </div>
        <div class="p-3">
          <div id="plansEmpty" class="text-muted">No plans to show.</div>
          <div id="plansLoader" style="display:none">Loading plans…</div>
          <div id="plansHost"></div>
        </div>
      </div>
    </div>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['ajax']) && $_POST['ajax'] === 'plans') {

    while (ob_get_level()) { ob_end_clean(); }

    $mobile = isset($_POST['mobileNumber']) ? preg_replace('/\D/', '', $_POST['mobileNumber']) : '';
    if (strlen($mobile) !== 10) {
        echo json_encode(['status' => '000', 'statusMessage' => 'Enter a valid 10 digit mobile number']);
        exit;
    }

    try {
        // ✅ Use your existing helper from header.php
        $resp = mobileRecharge_plan_api_run(['mobileNumber' => $mobile]);
        $decoded = json_decode($resp, true);
        if (!is_array($decoded)) {
            echo json_encode(['status' => '000', 'statusMessage' => 'Upstream returned non-JSON']);
            exit;
        }
        echo json_encode($decoded);
    } catch (Throwable $e) {
        echo json_encode(['status' => '000', 'statusMessage' => 'Server error', 'error' => $e->getMessage()]);
    }
    exit;
}
?>
    <!-- Display Datatable Section -->
    <?php if (isset($response['status']) && $response['status'] == '100') {  ?>
<div class="col-md-12 mb-2">
  <div class="card text-danger">
    <div class="card-header bg-danger text-white py-2">
      <span class="mr-auto">Recharge Details Mobile/DTH No: <strong><?= $phoneNumber ?? 'N/A'; ?></strong></span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <tbody>
          <?php if (!empty($response['statusMessage'])): ?>
          <tr>
            <td><strong>Status</strong></td>
            <td><?= htmlspecialchars($response['statusMessage']); ?></td>
          </tr>
          <?php endif; ?>
          <?php if (!empty($response['number'])): ?>
          <tr>
            <td><strong>Mobile/DTH Number</strong></td>
            <td><?= htmlspecialchars($response['number']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['amount'])): ?>
          <tr>
            <td><strong>Amount </strong></td>
            <td><?= htmlspecialchars($response['amount']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['provider'])): ?>
          <tr>
            <td><strong>Provider</strong></td>
            <td><?= htmlspecialchars($response['provider']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (!empty($response['message'])): ?>
          <tr>
            <td><strong>Message</strong></td>
            <td><?= htmlspecialchars($response['message']); ?></td>
          </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
    <?php } ?>
</div>
<!-- Modal to show Commission List -->
<div class="modal fade" id="showDetailsModal" tabindex="-1" role="dialog" aria-labelledby="showDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document"><!-- large width for table -->
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="showDetailsModalLabel">Commission List</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

        <?php
        // Fetch all operators
        $operators = db_fetch_all("operators"); // <-- adjust if you use another helper

        if (!empty($operators)) {
            echo '<div class="table-responsive">';
            echo '<table class="table table-bordered table-striped mb-0">';
            echo '<thead class="thead-light">
                    <tr>
                      <th>#</th>
                      <th>Operator Name</th>
                      <th>Type</th>
                      <th class="text-right">Commission (%)</th>
                    </tr>
                  </thead><tbody>';
            $i=1;
            foreach ($operators as $row) {
                $name  = $row['operator_name'] ?? 'NA';
                $type  = $row['operator_type'] ?? 'NA';
                $comm  = $row['plan_operator_id'] ?? '0';

                echo '<tr>';
                echo '<td>'. $i++ .'</td>';
                echo '<td>'. htmlspecialchars($name) .'</td>';
                echo '<td>'. htmlspecialchars($type) .'</td>';
                echo '<td class="text-center">'. number_format((float)$comm, 2) .'</td>';
                echo '</tr>';
            }
            echo '</tbody></table></div>';
        } else {
            echo '<div class="text-danger">No operators found.</div>';
        }
        ?>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
  // Build Operator dropdown once the page is ready
  document.addEventListener("DOMContentLoaded", function () {
    const operators = [
      { code: "A",  name: "AIRTEL" },
      { code: "RC", name: "RELIANCE JIO" },
      { code: "V",  name: "VODAFONE (VI)" },
      { code: "I",  name: "IDEA (VI)" },
      { code: "BT", name: "BSNL TOPUP" },
      { code: "BR", name: "BSNL - STV" },
      { code: "ATV", name: "AIRTEL DIGITAL TV (DTH)" },
      { code: "DTV", name: "DISH TV (DTH)" },
      { code: "STV", name: "SUN DIRECT (DTH)" },
      { code: "TTV", name: "TATA SKY (DTH)" },
      { code: "VTV", name: "VIDEOCON D2H (DTH)" },
    ];
    const stateSelect = document.getElementById("operatorName");
    operators.forEach(op => {
      const option = document.createElement("option");
      option.value = op.code;
      option.textContent = op.name;
      stateSelect.appendChild(option);
    });
  });

  (function(){
    const input  = document.getElementById('mobileInput');
    const btn    = document.getElementById('fetchPlansBtn');
    const host   = document.getElementById('plansHost');
    const empty  = document.getElementById('plansEmpty');
    const loader = document.getElementById('plansLoader');
    const errEl  = document.getElementById('plansError');
    const select = document.getElementById('operatorName');

    function digits(str){ return (str.match(/\d/g)||[]).join(''); }

    // Enable/disable the button instead of hiding it
    function toggleBtn(){
      const d = digits(input.value);
      btn.disabled = (d.length !== 10);
      if (d.length !== 10) { errEl.style.display='none'; host.innerHTML=''; empty.textContent='No plans to show.'; }
    }
    input.addEventListener('input', toggleBtn);
    toggleBtn();

    // Allow pressing Enter in the input to trigger fetch when 10 digits entered
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !btn.disabled) btn.click();
    });

    btn.addEventListener('click', async function(){
      const mobile = digits(input.value);
      if (mobile.length !== 10) return;

      errEl.style.display = 'none';
      loader.style.display = 'block';
      empty.textContent = 'Fetching plans…';
      host.innerHTML = '';

      try {
        const res = await fetch(location.href, {
          method: 'POST',
          headers: {'Content-Type':'application/x-www-form-urlencoded','Accept':'application/json'},
          cache: 'no-store',
          body: new URLSearchParams({ ajax: 'plans', mobileNumber: mobile })
        });

        const text = await res.text();
        const json = JSON.parse(text.slice(text.indexOf('{')));

        // If API returns success block with operator/circle, auto-select operator
        if (json && (json.status === '100' || json.status === 100)) {
          if (json.operator) {
            selectOperatorFromName(json.operator);
          }
        }

        renderPlans(json);
      } catch(e){
        errEl.textContent = 'Network error while fetching plans: ' + (e.message || e);
        errEl.style.display = 'block';
        empty.textContent = '—';
      } finally {
        loader.style.display = 'none';
      }
    });

    // Map API operator text to your <select> codes
    function selectOperatorFromName(opName){
      const s = String(opName).toLowerCase();

      // prefer VI->Vodafone option (code "V") by default
      const map = {
        'airtel': 'A',
        'reliance jio': 'RC',
        'jio': 'RC',
        'vi': 'V',
        'vodafone': 'V',
        'vodafone idea': 'V',
        'idea': 'I',
        // fallback guesses for BSNL (choose TOPUP by default)
        'bsnl': 'BT'
      };

      // find best key contained in the operator string
      let code = null;
      for (const key in map) {
        if (s.includes(key)) { code = map[key]; break; }
      }
      if (code) {
        select.value = code;
        // fire change event in case you bind anything later
        select.dispatchEvent(new Event('change'));
      }
    }

    // Render the plans (Popular group first)
    function renderPlans(payload){
      const groupings = (payload && payload.plans && Array.isArray(payload.plans.groupings))
        ? payload.plans.groupings : [];

      if (!groupings.length) { empty.textContent = 'No plans found.'; return; }
      empty.textContent = '';

      const popular = groupings.filter(g => (g.name || '').toLowerCase() === 'popular');
      const others  = groupings.filter(g => (g.name || '').toLowerCase() !== 'popular');
      const ordered = popular.concat(others);

      let html = '';
      ordered.forEach(g => {
        const list = g.productList || [];
        if (!list.length) return;

        html += `<h5 class="mb-2 mt-2">${escapeHtml(g.name || 'Plans')}
                   <span class="badge badge-light">${list.length}</span></h5>`;
        html += `<div class="table-responsive"><table class="table table-bordered table-striped">
          <thead class="thead-light">
            <tr><th>Price</th><th>Validity</th><th>Data</th><th>Talktime</th><th>SMS</th><th>Description</th></tr>
          </thead><tbody>`;

        list.forEach(p => {
          html += `<tr>
            <td>₹${escapeHtml(p.price)}</td>
            <td>${escapeHtml(p.validity ?? 'NA')}</td>
            <td>${escapeHtml(p.data ?? 'NA')}</td>
            <td>${escapeHtml(p.talktime ?? 'NA')}</td>
            <td>${escapeHtml(p.sms ?? 'NA')}</td>
            <td>${escapeHtml(p.description ?? '')}</td>
          </tr>`;
        });
        html += `</tbody></table></div>`;
      });

      host.innerHTML = html || '<div class="text-muted">No plans found.</div>';
    }

    function escapeHtml(x){
      return String(x ?? '').replace(/[&<>"']/g, s => (
        {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s]
      ));
    }
  })();
</script>
<?php
} else {
   require_once("404.php");
}
} else {
   awal_alert_msg('You Do Not Have Any Recharge Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
