<?php

$parent_id = (int)($_SESSION['parent_id'] ?? 0);
$user_id = (int)($_SESSION['userid'] ?? 0);
$id = ($parent_id > 0) ? (int)$parent_id : (int)$user_id;

$mikrotikConnect = false;
$mikrotikId = (int)($newMikrotikId ?? 0);
// $disconnect_days_data =$obj->rawSqlSingle("SELECT disconnect_date FROM _reseller_createuser WHERE UserId=$id");
// var_dump($disconnect_days_data);
$mk = null;
$mkObj = null;

$mik_id = 0;
$mik_ip = null;


if ($obj->tableExists('re_mikrotik_user')) {
  $mk = $obj->details_by_cond('re_mikrotik_user', "user_id = $user_id AND status= 1");

  if (!empty($mk)) {
    $mik_id = $mk['id'];
    $mik_ip = $mk['mik_ip'];
  }
  if (!empty($mk['mik_ip']) && !empty($mk['mik_port']) && !empty($mk['mik_username']) && !empty($mk['mik_password'])) {
    $mkObj = new Mikrotik($mk['mik_ip'], $mk['mik_port'], $mk['mik_username'], $mk['mik_password']);

    if ($mkObj->connected) {
      $mikrotikConnect = true;
    }
  }
}

$last = $obj->details_by_cond("re_tbl_agent", "1=1 ORDER BY ag_id DESC");
$nextId = (int)($last['ag_id'] ?? 0) + 1;

if ($nextId < 1000) $STD = "CUS0" . $nextId;
elseif ($nextId < 10000) $STD = "CUS0" . $nextId;
else $STD = "CUS" . $nextId;

$resellerSingle = $obj->details_by_cond('_reseller_createuser', "UserId='$id'");
$disconnectDate = $resellerSingle['disconnect_date'] ?? null;


if (!empty($_SESSION['userid'])) {

  if (isset($_POST['submit'])) {
    extract($_POST);

    $disconnectDate = $resellerSingle['disconnect_date'] ?? null;


    $disconnectDay = (int)$disconnectDate;

    $today = new DateTime();
    $target = new DateTime(date('Y-m-') . sprintf('%02d', $disconnectDay));
    if ($target < $today) {
        $target->modify('+1 month');
    }
    $t = date('t');
    $daysLeft = $today->diff($target)->days + 1;
    $re_taka_per_day = $re_taka / $t;
    $cus_taka_per_day = $taka / $t;

    $re_paid_amount = $daysLeft * $re_taka_per_day;
    $cus_paid_amount = $daysLeft * $cus_taka_per_day;


    $agentName = str_replace("'", '', (string)$name);
    $ip = str_replace(" ", '_', str_replace("'", '', (string)$ip));

    $int_mb = preg_replace('/[^.0-9]/', '', (string)$mb);
    $str_fr_mb = preg_replace('/[^a-zA-Z]/', '', (string)$mb);
    if ($str_fr_mb === 'kbps' || $str_fr_mb === 'kb') $int_mb = ($int_mb / 1024);
    if ($int_mb > 1000) $int_mb = 0;

    $date = date('Y-m-d');
    $date_time = date('Y-m-d H:i:s');
    $queue_password = $password;

    $disconnect_days = isset($disconnect_days) ? (int)$disconnect_days : 0;
    if ($disconnectDay == 0) {
      $daysLeft = 0;
    }

    $disconnectDate = date('Y-m-d', strtotime("+$daysLeft days"));

          // balance check
      if (($resellerSingle['balance'] ?? 0) < (float)$re_paid_amount) {
        echo '<script>alert("Insufficient balance");</script>';
        echo '<script>window.location="?page=reseller-all-customer-list";</script>';
        exit; // stop execution
      }
  

    $form_data_re_tbl_agent = [
      'ag_name' => $agentName,
      'ag_mobile_no' => str_replace("'", '', (string)$mobile),
      'ag_office_address' => str_replace("'", "", (string)$details),
      'taka' => str_replace("'", '', (string)$taka),
      're_taka' => str_replace("'", '', (string)$re_taka),
      'mb' => str_replace("'", '', (string)$mb),
      'int_mb' => str_replace("'", '', (string)$int_mb),
      'queue_password' => $queue_password,
      'cus_id' => $STD,
      'bill_cat' => 1,
      'billgenerate' => 1,
      'ag_status' => 1,
      'ip' => trim($ip),
      'regular_mobile' => str_replace("'", '', (string)$regularmobile),
      'zone' => (int)$zone,
      'national_id' => str_replace("'", '', (string)$national_id),
      'mac_address' => str_replace("'", '', (string)$macaddress),
      'entry_by' => $id,
      'entry_date' => $date,
      'connection_date' => date('Y-m-d', strtotime((string)$con_date)),
      'update_by' => $id,
      'billing_person_id' => $id,
      'bill_date' => (int)$bill_date,
      'mikrotik_id' => $mik_id,
      'reseller_package'  => $package,
      'mikrotik_disconnect' => $disconnectDate,
      'ag_status' => $ag_status,
    ];

    $takaVal = (float)$taka;
    $form_data_re_tbl_agent['dueadvance'] = $takaVal;
    $form_data_re_tbl_agent['generate_amount'] = $takaVal;
    $form_data_re_tbl_agent['paid_amount'] = 0;

    $connect_charge = (float)($connect_charge ?? 0);
    $connection_charge_due_amount = (float)($connection_charge_due_amount ?? 0);
    $previous_due = (float)($previous_due ?? 0);
    $opening_amount = (float)($opening_amount ?? 0);
    $discount = (float)($discount ?? 0);
    $running_month_due_amount = (float)($running_month_due_amount ?? 0);

    if ($connect_charge > 0) {
      $connect_charge = ($connect_charge > $connection_charge_due_amount) ? $connect_charge : $connection_charge_due_amount;
      $form_data_re_tbl_agent['connect_charge'] = $connect_charge;
      $form_data_re_tbl_agent['paid_amount'] += $connect_charge;
    }

    if ($connection_charge_due_amount > 0) {
      $form_data_re_tbl_agent['connection_charge_due'] = $connection_charge_due_amount;
      $form_data_re_tbl_agent['dueadvance'] += $connection_charge_due_amount;
      if ($connect_charge > 0) $form_data_re_tbl_agent['paid_amount'] -= $connection_charge_due_amount;
    }

    if ($previous_due > 0) {
      $form_data_re_tbl_agent['previous_due'] = $previous_due;
      $form_data_re_tbl_agent['dueadvance'] += $previous_due;
    }

    if ($opening_amount > 0) {
      $form_data_re_tbl_agent['paid_amount'] += $opening_amount;
      $form_data_re_tbl_agent['dueadvance'] -= $opening_amount;
      $form_data_re_tbl_agent['bill_status'] = 1;
      $form_data_re_tbl_agent['payment_status'] = 1;
    }

    if ($discount > 0) {
      $form_data_re_tbl_agent['discount'] = $discount;
      $form_data_re_tbl_agent['dueadvance'] -= $discount;
      $form_data_re_tbl_agent['bill_status'] = 1;
    }

    if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {
      $uploadDir = "asset/uploads/";
      $desiredPath = dirname(__DIR__) . '/' . $uploadDir;

      $fileName = $_FILES["image"]["name"];
      $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
      $uniqueName = time() . uniqid() . "." . $fileExtension;

      $forDatabase = $uploadDir . $uniqueName;
      $filePath = $desiredPath . $uniqueName;

      if (move_uploaded_file($_FILES["image"]["tmp_name"], $filePath)) {
        $form_data_re_tbl_agent['id_photo'] = $forDatabase;
      }
    }

    $agent_add = null;

      //insert data

      $agent_add = $obj->Insert_data("re_tbl_agent", $form_data_re_tbl_agent);

      // balance deduct & insert account record
      $obj->Update_data(
        '_reseller_createuser',
        ['balance' => ($resellerSingle['balance'] ?? 0) - (float)$re_paid_amount],
        "UserId='$id'"
      );

      $reFrom = [
        'reseller_id' => $id,
        'agent_id'    => $agent_add,
        'amount'      => (float)$re_paid_amount,
        'type'        => 5,
        'description' => "Balance recharge for new customer, disconnect date $disconnectDate",
        'entry_by'    => $id,
        'entry_date'  => $date,
      ];

      $resaccid = $obj->Insert_data("re_tbl_reseller_account", $reFrom);

      $obj->Insert_data("re_tbl_account", [
            'agent_id'            => $agent_add,
            'cus_id'              => $STD,
            'acc_amount'          => $cus_paid_amount,
            'acc_type'            => '3',
            'acc_description'     => "Bill collection at $date_time",
            'entry_by'            => $id,
            'entry_date'          => $date,
            'update_by'           => $id,
            'reseller_id'         => $id,
            'reseller_account_id' => $resaccid
        ]);


      // $agent_add = $obj->Insert_data("re_tbl_agent", $form_data_re_tbl_agent);



    if ($agent_add) {



      //activity log
      $result = $obj->resellerHistoryLog([
        're_id'        => $user_id,
        'header'       => 'Customer Create',
        'descriptions' => 'Create Customer Name: "' . $agentName . '" And Cus ID: "' . $STD . '" Created.',
        'type'         => 'insert',
        'ag_id'        => $agent_add,
      ]);



      if ($previous_due > 0) {
        $obj->Insert_data("tbl_previous_due", [
          're_tbl_agent_id' => $agent_add,
          'previous_due_amount' => $previous_due,
          'update_by' => $id
        ]);
      }

      if (!empty($remarks)) {
        $obj->Insert_data("tbl_remarks", [
          'ag_id' => $agent_add,
          'remarks' => $remarks,
          'created_at' => date('Y-m-d', strtotime('first day of this month')),
          'entry_by' => $id,
          'updated_by' => $id
        ]);
      }

      if ($discount > 0) {
        $obj->Insert_data("re_bonus", [
          'customerID' => $agent_add,
          'amount' => $discount,
          'entry_date' => $date,
          'takenBy' => $id
        ]);
      }

      if ($opening_amount > 0) {
        $obj->Insert_data("re_tbl_account", [
          'cus_id' => $agent_add,
          'agent_id' => $agent_add,
          'acc_type' => '5',
          'acc_amount' => $opening_amount,
          'acc_description' => 'Opening and running month bill for connection of ' . $agentName,
          'entry_by' => $id,
          'entry_date' => $date_time,
          'update_by' => $id,
          'reseller_id' => $id,
          'reseller_account_id' => $resaccid,
        ]);
      }

      if ($connect_charge > 0) {
        $obj->Insert_data("re_tbl_account", [
          'cus_id' => $agent_add,
          'agent_id' => $agent_add,
          'acc_amount' => $connect_charge,
          'acc_type' => '4',
          'acc_description' => 'Connection charge of ' . $agentName,
          'entry_by' => $id,
          'entry_date' => $date_time,
          'update_by' => $id
        ]);
      }

      if (($running_month_due_amount > 0) || ($connection_charge_due_amount > 0)) {
        $obj->Insert_data("tbl_due_opening_amount_and_con_charge", [
          're_tbl_agent_id' => $agent_add,
          'running_month_due' => $running_month_due_amount,
          'connection_charge_due' => $connection_charge_due_amount,
          'entry_by' => $id
        ]);
      }


      if ($mikrotikConnect) {
        $result = $obj->reCreateNewSecret($mik_id, $ip, $password, $mb, $remarks);


        if (($_POST['ag_status'] == 0) || ($_POST['ag_status'] == 3)) {
          $obj->reDisableSingleSecret($mik_id, $_POST['ip']);
        }
      }



      if (isset($sms_check)) {
        $customer = $obj->raw_sql("SELECT * FROM re_tbl_agent WHERE ag_id=$agent_add AND entry_by=$id");
        $customer = $customer[0];
        $smsPhone = "88" . strval($customer['ag_mobile_no'] ?? '');




        $var_replacement = [
          '{CUSTOMER_NAME}' => $customer['ag_name'] ?? '',
          '{PACKAGE_NAME}' => $customer['mb'] ?? '',
          '{MONTHLY_BILL}' => $customer['taka'] ?? '',
          '{CUSTOMER_ID}' => $customer['cus_id'] ?? '',
          '{IP_ADDRESS}' => $customer['ip'] ?? '',
        ];

        $newCustomerSmsInfo = $obj->rawSqlSingle("SELECT * FROM re_tbl_sms  WHERE reseller_id='$id' AND status=4  AND smshead='active'");


        if ($newCustomerSmsInfo && isset($newCustomerSmsInfo['smsbody'])) {
          $smsBodyTpl = $newCustomerSmsInfo['smsbody'] ?? '';
          $smsBody = strtr($smsBodyTpl, $var_replacement);

          if (!empty($smsBody) && !empty($smsPhone)) {
            try {
              $result = $obj->reSendsms($smsPhone, $smsBody, $id);
            } catch (\Throwable $th) {
              echo $th;
            }
          }
        }
      }

      $obj->notificationStore('Customer Created Successfully', 'success');

      if (!empty($connect_charge) || !empty($opening_amount) || !empty($running_month_due_amount) || !empty($connection_charge_due_amount)) {
        if (isset($print_invoice)) {
          echo "<script>window.open('../pdf/new_cus_invoice.php?agent=$agent_add','_blank');</script>";
        }
      }

      echo '<script>window.location="?page=reseller-all-customer-list";</script>';
      exit;
    } else {
      $obj->notificationStore('Insert Failed', 'danger');
      echo '<script>window.location="?page=reseller-all-customer-list";</script>';
      exit;
    }
  }
}

$rBalance = $obj->get_sum_by_cond('balance', 're_vw_user_info', "UserType='RE' AND UserId=$id");
?>

<style>
  :root {
    --bg: #f6f8fb;
    --card: #fff;
    --text: #111827;
    --muted: #6b7280;
    --border: #e5e7eb;
    --shadow: 0 10px 25px rgba(17, 24, 39, .06);
    --radius: 14px;
  }

  .page-wrap {
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 14px;
  }

  .head {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 12px;
  }

  .h-title {
    margin: 0;
    font-size: 18px;
    font-weight: 900;
    color: var(--text);
  }

  .h-sub {
    margin: 5px 0 0;
    color: var(--muted);
    font-size: 12px;
  }

  .cardx {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
  }

  .cardx .cardx-h {
    padding: 12px 14px;
    border-bottom: 1px solid var(--border);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
  }

  .badge-soft {
    display: inline-block;
    padding: 6px 10px;
    border-radius: 999px;
    font-weight: 900;
    font-size: 12px;
    background: rgba(59, 130, 246, .10);
    color: #1d4ed8;
  }

  .cardx .cardx-b {
    padding: 14px;
  }

  .form-control {
    border-radius: 10px;
    border: 1px solid var(--border);
    box-shadow: none;
    height: 38px;
  }

  textarea.form-control {
    height: auto;
  }

  .help {
    font-size: 12px;
    color: var(--muted);
    margin-top: 6px;
  }

  .btn {
    border-radius: 10px !important;
    font-weight: 900;
  }

  .sep-title {
    margin: 0 0 10px;
    font-weight: 900;
    color: var(--text);
    font-size: 13px;
  }

  .hr-soft {
    border-top: 1px dashed var(--border);
    margin: 12px 0;
  }

  .req {
    color: #ef4444;
  }

  @media (max-width:767px) {
    .page-wrap {
      padding: 10px;
    }
  }
</style>

<div class="page-wrap">
  <div class="head">
    <div>
      <h6 class="h-title">Create New Customer: <?php echo htmlspecialchars($STD); ?></h6>
      <div class="h-sub">
        <?php echo ($mikrotikConnect ? 'Mikrotik connected' : 'Mikrotik not connected'); ?>
      </div>
    </div>
    <div class="badge-soft">Available Balance: <?php echo isset($rBalance) ? $rBalance : 0; ?></div>
  </div>

  <div class="cardx">
    <div class="cardx-h">
      <div style="font-weight:900;">
        Customer Info
      </div>
      <?php if (!$mikrotikConnect) { ?>
        <span class="label label-danger" style="border-radius:999px; padding:6px 10px; font-weight:900;">Mikrotik connection failed</span>
      <?php } ?>
    </div>

    <div class="cardx-b">
      <form role="form" enctype="multipart/form-data" method="post" id="customerCreateForm">

        <div class="row">
          <div class="col-md-6">
            <h6 class="sep-title">Connection</h6>

            <div class="form-group">
              <label>Client IP / Secret <span class="req">*</span></label>
              <input type="text" name="ip" class="form-control" id="clientIp" placeholder="Unique IP/Secret" required onkeypress="return noSpace(event)">
              <div id="checkavailablityclientIp" class="help"></div>
            </div>

            <div class="form-group">
              <label>Queue Password <span class="req">*</span></label>
              <input type="password" name="password" class="form-control" required placeholder="Secret password">
            </div>

            <div class="form-group">
              <label>Customer/Company Name <span class="req">*</span></label>
              <input type="text" name="name" class="form-control" required>
            </div>

            <div class="form-group">
              <label>SMS Mobile No <span class="req">*</span></label>
              <input onkeypress="return numbersOnly(event)" required value="01" type="text" name="mobile" class="form-control">
            </div>

            <div class="form-group">
              <label>Connection Date <span class="req">*</span></label>
              <input type="text" readonly name="con_date" value="<?php echo date('d-m-Y') ?>" class="form-control" required autocomplete="off">
            </div>

            <div class="form-group">
              <label>Zone</label>
              <select class="form-control " name="zone">
                <option value="">Select</option>
                <?php foreach ($obj->view_all_by_cond('re_tbl_zone', "created_by=$user_id OR reseller_id=$parent_id") as $singleZone) { ?>
                  <option value="<?php echo (int)$singleZone['zone_id'] ?>"><?php echo htmlspecialchars($singleZone['zone_name']) ?></option>
                <?php } ?>
              </select>
            </div>

            <div class="form-group">
              <label>Others Mobile Number</label>
              <input type="text" name="regularmobile" class="form-control">
            </div>

            <div class="form-group">
              <label>Mac Address</label>
              <input type="text" name="macaddress" class="form-control">
            </div>

            <div class="form-group">
              <label>National Id/Passport Number</label>
              <input type="text" name="national_id" class="form-control">
            </div>

            <div class="form-group">
              <label>National Id/Passport Image</label>
              <input type="file" accept="image/*" name="image" class="form-control">
            </div>
          </div>

          <div class="col-md-6">
            <h6 class="sep-title">Package & Billing</h6>

            <div class="form-group">
              <label>Package <span class="req">*</span></label>
              <select class="form-control " name="package" id="packageListd" required>
                <option value="">Select</option>
                <?php foreach ($obj->view_all_by_cond('re_tbl_package', "reseller_id=$user_id OR reseller_id=$parent_id") as $singlePackage) { ?>
                  <option
                    data-speed="<?php echo htmlspecialchars($singlePackage['net_speed']); ?>"
                    data-bill="<?php echo htmlspecialchars($singlePackage['bill_amount']); ?>"
                    data-re_taka="<?php echo htmlspecialchars($singlePackage['re_bill_amount']); ?>"
                    value="<?php echo htmlspecialchars($singlePackage['package_name']); ?>">
                    <?php echo htmlspecialchars(str_replace('_', '-', $singlePackage['package_name'])); ?>
                  </option>
                <?php } ?>
              </select>
            </div>

            <div class="form-group" style="display:none" id="netSpeed">
              <label>Speed <span class="req">*</span></label>
              <input type="text" name="mb" class="form-control" readonly required placeholder="Select package">
            </div>

            <div class="form-group" id="billAmount">
              <label>Bill Amount <span class="req">*</span></label>
              <input type="hidden" name="re_taka" required class="form-control" value="0">
              <input onkeypress="return numbersOnly(event)" type="text" name="taka" required class="form-control" placeholder="Monthly bill">
            </div>

            <!-- <div class="form-group">
              <label>Disconnect Days <span class="req">*</span></label>
              <select name="disconnect_days" class="form-control" required>
                <option value="0">Today (Free)</option>
                <option value="1">1 Day (Free)</option>
                <option value="30">1 Month(Paid) </option>
              </select>
            </div> -->

            

            <div class="row">
              <div class="col-md-12">
                <div class="form-group">
                  <label>Connection Charge Paid Amount</label>
                  <input onkeypress="return numbersOnly(event)" type="text" name="connect_charge" min="0" value="0" required class="form-control">
                </div>
              </div>

              <div class="col-md-6" style="display:none;">
                <div class="form-group">
                  <label>Connection Charge Due Amount</label>
                  <input onkeypress="return numbersOnly(event)" type="text" name="connection_charge_due_amount" min="0" value="0" required class="form-control">
                </div>
              </div>

              <div class="col-md-6" style="display:none;">
                <div class="form-group">
                  <label>Running Bill Due Amount</label>
                  <input onkeypress="return numbersOnly(event)" type="text" name="running_month_due_amount" id="running_month_due_amount" min="0" value="0" required class="form-control">
                </div>
              </div>

              <div class="col-md-6" style="display:none;">
                <div class="form-group">
                  <label>Previous Bill Due Amount</label>
                  <input onkeypress="return numbersOnly(event)" type="text" name="previous_due" min="0" value="0" required class="form-control">
                </div>
              </div>

              <div class="col-md-6" style="display:none;">
                <div class="form-group">
                  <label>Running Month Bill Paid Amount</label>
                  <input onkeypress="return numbersOnly(event)" type="text" name="opening_amount" id="opening_amount" min="0" value="0" required class="form-control">
                </div>
              </div>

              <div class="col-md-6" style="display:none;">
                <div class="form-group">
                  <label>Running Month Bill Discount Amount</label>
                  <input onkeypress="return numbersOnly(event)" type="text" readonly name="discount" id="discount" min="0" value="0" required class="form-control">
                </div>
              </div>
            </div>

            <div class="form-group" style="display:none;">
              <label>Bill Date</label>
              <input onkeypress="return numbersOnly(event)" type="text" value="<?php echo date('d') ?>" required name="bill_date" class="form-control">
            </div>

            <div class="form-group">
              <label>Address </label>
              <textarea class="form-control" name="details" rows="3"></textarea>
            </div>

            <div class="form-group">
              <label>Remarks/Comment</label>
              <textarea class="form-control" name="remarks" rows="2"></textarea>
            </div>

            <div class="form-group">
              <label>Status</label>
              <select class="form-control" required="required" name="ag_status" id="status">
                <option value="1">Active</option>
                <option value="0">Inactive</option>
              </select>
            </div>

          </div>
        </div>

        <div class="hr-soft"></div>

        <div class="row">
          <div class="col-sm-2 m-auto mb-4">
            <div class="form-switch switch-success d-flex align-items-center gap-3">
              <input class="form-check-input" type="checkbox" role="switch" id="smssend" name="sms_check" value="sms_check" checked>
              <label class="form-check-label line-height-1 fw-medium text-secondary-light" for="yes">SMS Notification Send</label>
            </div>
          </div>

          <div class="col-md-12 text-center">
            <button type="submit" class="btn btn-success" name="submit">
              <i class="fa fa-save"></i> Save New Customer
            </button>
            <a href="?page=reseller-all-customer-list" class="btn btn-default">
              Cancel
            </a>
          </div>
        </div>

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

<?php $obj->start_script(); ?>
<script>
  function numbersOnly(e) {
    var unicode = e.charCode ? e.charCode : e.keyCode;
    if (unicode != 8) {
      if ((unicode < 2534 || unicode > 2543) && (unicode < 48 || unicode > 57)) return false;
    }
  }

  function noSpace(e) {
    if (e.which == 32) return false;
  }

  $(document).ready(function() {

    if ($.fn.select2) {
      $('.select2').select2({
        allowClear: true,
        width: '100%'
      });
    }

    $('#clientIp').on('focusout', function() {

      var clientIpData = $(this).val();
      var inputField = $(this);

      if (!clientIpData) {
        $('#checkavailablityclientIp').html('');
        return;
      }

      $.post('pages/resellers/customer/add_ajax_data.php', {
          ip: clientIpData
        },
        function(data) {

          if (data == 0) {

            $('#checkavailablityclientIp')
              .html('<span style="color:red;">Already exists</span>');

            inputField.val('');
            inputField.focus();

          } else {
            $('#checkavailablityclientIp')
              .html('<span style="color:green;">IP Available</span>');
          }
        }
      );

    });

    $('#packageListd').on('change', function() {
      var $opt = $(this).find(':selected');
      var speed = $opt.data('speed') || '';
      var bill = $opt.data('bill') || '';
      var re_taka = $opt.data('re_taka') || '';

      $("div#billAmount input[name='taka']").val(bill);
      $("div#netSpeed input[name='mb']").val(speed);
      // $("#opening_amount").val(bill);
      $("input[name='re_taka']").val(re_taka);

      $.ajax({
        url: 'page/resellers/reseller/customer/get_taka_ajax.php',
        method: 'POST',
        data: {
          monthlyBill: bill,
          re_taka: re_taka
        },
        success: function(response) {
          try {
            var result = JSON.parse(response);
            if (result.status === 'error') {
              alert(result.message || 'Error');
              window.location.href = "?page=reseller-new-customer-add";
            } else {
              if ($('#paid_days').length) $('#paid_days').val(result.paid_days);
            }
          } catch (e) {}
        }
      });
    });

    $("input[name='taka']").on('change', function() {
      $("#opening_amount").val($(this).val());
    });

    $('#opening_amount').on('change', function() {
      var openingAmount = parseFloat($("#opening_amount").val() || 0);
      var mainamount = parseFloat($("div#billAmount input[name='taka']").val() || 0);
      var dueAmount = parseFloat($("#running_month_due_amount").val() || 0);

      var discount = (mainamount - dueAmount) - openingAmount;
      discount = (discount < 0) ? 0 : discount;
      $("#discount").val(discount);
    });

    $('#running_month_due_amount').on('change', function() {
      var dueAmount = parseFloat($(this).val() || 0);
      var mainamount = parseFloat($("div#billAmount input[name='taka']").val() || 0);
      var paid = mainamount - dueAmount;
      paid = (paid < 0) ? 0 : paid;
      $("#opening_amount").val(paid);
    });

  });
</script>
<?php $obj->end_script(); ?>