<?php

include '../managers/menu.php';

if (!(UserHasPerm('manage_pricing'))) {
  StopAndDie();
}

function getMNBExchange($curr = 'USD') {
    $url = 'http://www.mnb.hu/arfolyamok.asmx';
    $soap = '<?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.mnb.hu/webservices/">
    <soap:Body>
    <web:GetCurrentExchangeRates/>
    </soap:Body>
    </soap:Envelope>';

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $soap,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: text/xml; charset=utf-8',
            'SOAPAction: "http://www.mnb.hu/webservices/MNBArfolyamServiceSoap/GetCurrentExchangeRates"'
        ]
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $decoded = htmlspecialchars_decode(htmlspecialchars_decode($response, ENT_QUOTES), ENT_QUOTES);

    if (preg_match('/curr="' . preg_quote($curr, '/') . '"\s*>\s*(\d+,\d+)/', $decoded, $m)) {
        $value = (float)str_replace(',', '.', $m[1]);
        return $value;
    }
    return null;
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "LoadCustomerType") {

    $return_array = [];

    $query = "SELECT DISTINCT type_name, currency FROM customer_types WHERE is_active = 1 ORDER BY type_name ASC";
    if ($result = $conn->query($query)) {
      while ($c_type = $result->fetch_assoc()) {
        $return_array[] = [
          "type_name" => $c_type['type_name'],
          "currency" => $c_type['currency']
        ];
      }
    }

    echo json_encode(array(
        'data' => $return_array,
        'result' => 'ok'
    ));

  } else if (htmlspecialchars($_POST["func"]) == "CreateCustomerType") {
    $type_name = ucfirst(trim(htmlspecialchars($_POST["type_name"])));
    $currency = strtoupper(trim(htmlspecialchars($_POST["currency"])));

    if (empty($type_name) || empty($currency)) {
      echo json_encode(array(
          'result' => 'Üres paraméterekkel nem hozhat létre vevőtípust'
      ));
    } else {

      $sql = mysqli_query($conn,"SELECT ct_id FROM customer_types WHERE is_active = 0 LIMIT 1");
      $data = mysqli_fetch_array($sql);
      if ($data != null) {
        $ct_id = $data["ct_id"];
        $sql = mysqli_query($conn,"UPDATE customer_types SET type_name='$type_name',currency='$currency',category_name='Alapértelmezett',price=0,is_active=1 WHERE ct_id = '$ct_id'");
      } else {
        $sql = mysqli_query($conn,"INSERT INTO customer_types(type_name, currency, category_name, price, is_active) VALUES ('$type_name','$currency','Alapértelmezett',1,1)");
      }
      echo json_encode(array( 'result' => 'ok' ));
    }
  } else if (htmlspecialchars($_POST["func"]) == "OpenCustomerType") {
    $type_name = htmlspecialchars($_POST["type_name"]);

    $return_array = [];
    $currency = '';

    $query = "SELECT * FROM customer_types WHERE type_name = '$type_name' and is_active = 1 ORDER BY category_name ASC";
    if ($result = $conn->query($query)) {
      while ($c_type = $result->fetch_assoc()) {
        $return_array[] = [
          "ct_id" => $c_type['ct_id'],
          "currency" => $c_type['currency'],
          "category_name" => $c_type['category_name'],
          "price" => $c_type['price'],
          "is_active" => $c_type['is_active']
        ];

        $currency = $c_type['currency'];
      }
    }

    echo json_encode(array(
        'data' => $return_array,
        'exchange' => (getMNBExchange($currency) ?: 'N/A'),
        'result' => 'ok'
    ));
  } else if (htmlspecialchars($_POST["func"]) == "EditCategoryName") {
    $type_name = htmlspecialchars($_POST["type_name"]);
    $category_name = ucfirst(trim(htmlspecialchars($_POST["category_name"])));
    $price = floatval($_POST["price"] ?? 0);

    if (empty($type_name) || empty($category_name)) {
      echo json_encode(array( 'result' => 'Üres paraméterekkel nem hozhat létre árkategóriát' ));
    } else {
      $sql = mysqli_query($conn,"SELECT currency FROM customer_types WHERE type_name = '$type_name' LIMIT 1");
      $data = mysqli_fetch_array($sql);
      if ($data == null) {
        echo json_encode(array( 'result' => 'Nem létező vevőtípus lett megadva' ));
      } else {
        $currency = $data['currency'];

        $sql = mysqli_query($conn,"SELECT ct_id FROM customer_types WHERE type_name = '$type_name' and category_name='$category_name'");
        $data = mysqli_fetch_array($sql);
        if ($data != null) {
          $ct_id = $data["ct_id"];
          $sql = mysqli_query($conn,"UPDATE customer_types SET type_name='$type_name',currency='$currency',category_name='$category_name',price=$price,is_active=1 WHERE ct_id = '$ct_id'");
        } else {
          $sql = mysqli_query($conn,"SELECT ct_id FROM customer_types WHERE is_active = 0 LIMIT 1");
          $data = mysqli_fetch_array($sql);
          if ($data != null) {
            $ct_id = $data["ct_id"];
            $sql = mysqli_query($conn,"UPDATE customer_types SET type_name='$type_name',currency='$currency',category_name='$category_name',price=$price,is_active=1 WHERE ct_id = '$ct_id'");
          } else {
            $sql = mysqli_query($conn,"INSERT INTO customer_types(type_name, currency, category_name, price, is_active) VALUES ('$type_name','$currency','$category_name',$price,1)");
          }
        }
      }

      echo json_encode(array( 'result' => 'ok' ));
    }
  } else if (htmlspecialchars($_POST["func"]) == "DisableCategory") {
    $ct_id = htmlspecialchars($_POST["ct_id"]);
    $sql = mysqli_query($conn,"UPDATE customer_types SET is_active = 0 WHERE ct_id = '$ct_id'");

    echo json_encode(array( 'result' => 'ok' ));
  }

  exit();
}

?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <title>Kezelőfelület</title>
  </head>
  <style>
    .content {
      display: flex;
      margin-left: 200px;
      min-height: calc(100% - 50px);
    }

    .sidebar {
      width: 280px;
      background-color: var(--toppanel);
      border-right: 1px solid #bdc3c7;
      display: flex;
      flex-direction: column;
      padding: 24px 16px;
      overflow-y: auto;
    }

    .sidebar-title {
      font-weight: bold;
      margin-bottom: 16px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .customer-type-list {
      list-style: none;
      margin-bottom: 24px;
    }

    .customer-type-item {
      padding: 12px 12px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.5s;
    }

    .customer-type-item:hover {
      background-color: var(--panelcolor);
      color: #ffffff;
    }

    .customer-type-item.active {
      background-color: var(--panelcolor);
      color: #ffffff;
      border-color: var(--panelcolor);
      font-weight: 500;
    }

    .add-customer-btn {
      height: unset;
      border: 2px dashed #bdc3c7;
      background-color: transparent;
      color: var(--panelcolor);
    }

    .add-customer-btn:hover {
      opacity: 1;
      border-color: var(--panelcolor);
      background-color: color-mix(in srgb, var(--panelcolor) 10%, #ffffff 90%);
    }

    .main-content {
      flex: 1;
      flex-direction: column;
      padding: 32px;
      padding-top: 0px;
      overflow-y: auto;
      display: none;
    }

    input.price {
      background-color: color-mix(in srgb, var(--panelcolor) 10%, #ffffff 90%);
      border: 2px dashed #bdc3c7;
      width: 100px !important;
      padding: 4px;
    }

    @media only screen and (max-width: 1145px) {
      .content {
        margin-left: 65px;
      }
    }
  </style>
  <body>
    <?php echo $menuhtml;?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content">

      <!-- Tartalmi rész kezdete -->

      <!-- SIDEBAR -->
      <aside class="sidebar">
        <div class="sidebar-title">Vevőtípusok</div>
        <ul class="customer-type-list" id="customer-type-list">
        </ul>
        <button class="add-customer-btn" onclick="CreateCustomerType()">+ Új típus</button>
      </aside>

      <!-- Main content -->

      <main class="main-content" id="main-content">
        <h1>Árazás</h1>
        <p style="position: absolute; float: right; top: 50px; right: 15px; opacity: 0.8;">1 <span id="c_currency"></span> = <span id="c_exchange"></span> HUF</p>
        <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 587px);"></div>

        <br clear="all">
        <div style="width: 100%; margin-top: 10px; display: inline; float: left; max-width: 800px;">
          <div class="tables" style="width: 100%">
            <table id="table">
              <thead>
                <tr style="top: 0px; position: sticky; z-index: 1;">
                  <th>Árkategória</th>
                  <th style="width: 200px;">Ár <small style="opacity: 0.8;"><small id="c_exchange_table"></small></small></th>
                  <th style="width: 200px;">Ár <small style="opacity: 0.8;"><small>HUF</small></small></th>
                </tr>
              </thead>
              <tbody>
              </tbody>
            </table>
          </div>
        </div>
      </main>

      <datalist id="currency-list">
        AFN"><option value="EUR"><option value="ALL"><option value="DZD"><option value="USD"><option value="AOA"><option value="XCD"><option value="XAD"><option value="ARS"><option value="AMD"><option value="AWG"><option value="AUD"><option value="AZN"><option value="BSD"><option value="BHD"><option value="BDT"><option value="BBD"><option value="BYN"><option value="BZD"><option value="XOF"><option value="BMD"><option value="INR"><option value="BTN"><option value="BOB"><option value="BOV"><option value="BAM"><option value="BWP"><option value="NOK"><option value="BRL"><option value="BND"><option value="BIF"><option value="CVE"><option value="KHR"><option value="XAF"><option value="CAD"><option value="KYD"><option value="CLP"><option value="CLF"><option value="CNY"><option value="COP"><option value="COU"><option value="KMF"><option value="CDF"><option value="NZD"><option value="CRC"><option value="CUP"><option value="XCG"><option value="CZK"><option value="DKK"><option value="DJF"><option value="DOP"><option value="EGP"><option value="SVC"><option value="ERN"><option value="SZL"><option value="ETB"><option value="FKP"><option value="FJD"><option value="XPF"><option value="GMD"><option value="GEL"><option value="GHS"><option value="GIP"><option value="GTQ"><option value="GBP"><option value="GNF"><option value="GYD"><option value="HTG"><option value="HNL"><option value="HKD"><option value="HUF"><option value="ISK"><option value="IDR"><option value="XDR"><option value="IRR"><option value="IQD"><option value="ILS"><option value="JMD"><option value="JPY"><option value="JOD"><option value="KZT"><option value="KES"><option value="KPW"><option value="KRW"><option value="KWD"><option value="KGS"><option value="LAK"><option value="LBP"><option value="LSL"><option value="ZAR"><option value="LRD"><option value="LYD"><option value="CHF"><option value="MOP"><option value="MKD"><option value="MGA"><option value="MWK"><option value="MYR"><option value="MVR"><option value="MRU"><option value="MUR"><option value="XUA"><option value="MXN"><option value="MXV"><option value="MDL"><option value="MNT"><option value="MAD"><option value="MZN"><option value="MMK"><option value="NAD"><option value="NPR"><option value="NIO"><option value="NGN"><option value="OMR"><option value="PKR"><option value="PAB"><option value="PGK"><option value="PYG"><option value="PEN"><option value="PHP"><option value="PLN"><option value="QAR"><option value="RON"><option value="RUB"><option value="RWF"><option value="SHP"><option value="WST"><option value="STN"><option value="SAR"><option value="RSD"><option value="SCR"><option value="SLE"><option value="SGD"><option value="XSU"><option value="SBD"><option value="SOS"><option value="SSP"><option value="LKR"><option value="SDG"><option value="SRD"><option value="SEK"><option value="CHE"><option value="CHW"><option value="SYP"><option value="TWD"><option value="TJS"><option value="TZS"><option value="THB"><option value="TOP"><option value="TTD"><option value="TND"><option value="TRY"><option value="TMT"><option value="UGX"><option value="UAH"><option value="AED"><option value="USN"><option value="UYU"><option value="UYI"><option value="UYW"><option value="UZS"><option value="VUV"><option value="VES"><option value="VED"><option value="VND"><option value="YER"><option value="ZMW"><option value="ZWG"><option value="XBA"><option value="XBB"><option value="XBC"><option value="XBD"><option value="XTS"><option value="XXX"><option value="XAU"><option value="XPD"><option value="XPT"><option value="XAG"><option value="AFA"><option value="FIM"><option value="ALK"><option value="ADP"><option value="ESP"><option value="FRF"><option value="AOK"><option value="AON"><option value="AOR"><option value="ARA"><option value="ARP"><option value="ARY"><option value="RUR"><option value="ATS"><option value="AYM"><option value="AZM"><option value="BYB"><option value="BYR"><option value="BEC"><option value="BEF"><option value="BEL"><option value="BOP"><option value="BAD"><option value="BRB"><option value="BRC"><option value="BRE"><option value="BRN"><option value="BRR"><option value="BGJ"><option value="BGK"><option value="BGL"><option value="BUK"><option value="HRD"><option value="HRK"><option value="CUC"><option value="ANG"><option value="CYP"><option value="CSJ"><option value="CSK"><option value="ECS"><option value="ECV"><option value="GQE"><option value="EEK"><option value="XEU"><option value="GEK"><option value="DDM"><option value="DEM"><option value="GHC"><option value="GHP"><option value="GRD"><option value="GNE"><option value="GNS"><option value="GWE"><option value="GWP"><option value="ITL"><option value="ISJ"><option value="IEP"><option value="ILP"><option value="ILR"><option value="LAJ"><option value="LVL"><option value="LVR"><option value="LSM"><option value="ZAL"><option value="LTL"><option value="LTT"><option value="LUC"><option value="LUF"><option value="LUL"><option value="MGF"><option value="MVQ"><option value="MLF"><option value="MTL"><option value="MTP"><option value="MRO"><option value="MXP"><option value="MZE"><option value="MZM"><option value="NLG"><option value="NIC"><option value="PEH"><option value="PEI"><option value="PES"><option value="PLZ"><option value="PTE"><option value="ROK"><option value="ROL"><option value="STD"><option value="CSD"><option value="SLL"><option value="SKK"><option value="SIT"><option value="RHD"><option value="ESA"><option value="ESB"><option value="SDD"><option value="SDP"><option value="SRG"><option value="CHC"><option value="TJR"><option value="TPE"><option value="TRL"><option value="TMM"><option value="UGS"><option value="UGW"><option value="UAK"><option value="SUR"><option value="USS"><option value="UYN"><option value="UYP"><option value="VEB"><option value="VEF"><option value="VNC"><option value="YDD"><option value="YUD"><option value="YUM"><option value="YUN"><option value="ZRN"><option value="ZRZ"><option value="ZMK"><option value="ZWC"><option value="ZWD"><option value="ZWN"><option value="ZWR"><option value="ZWL"><option value="XFO"><option value="XRE"><option value="XFU">
      </datalist>

      <br clear="all"><br><br>
      <!-- Tartalmi rész vége -->

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <script type="text/javascript">

      var price_category = [<?php echo $print_price_category;?>]
      function LoadCustomerType() {
        const body = 'func=LoadCustomerType';
        get_POST_information("pricing.php", body, function(text) {
          let response = JSON.parse(text);
          if (response.result == "ok") {
            const list = document.getElementById("customer-type-list");
            list.innerHTML = '';

            response.data.forEach((item, i) => {
              list.innerHTML += `<li class="customer-type-item" id="${item.type_name}_sidebar" onclick="SelectCustomerType('${item.type_name}')">${item.type_name} - <small style="opacity: 0.8;">${item.currency}</small></li>`;
            });


          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          GenerateAlerts("error", "Hálózati hiba!");
        });

      }
      LoadCustomerType();

      function CreateCustomerType(type_name = "", currency = "") {
        if (type_name == "" ||currency == "") {
          var id = GenerateID();
          var html = `
              <p><strong>Töltse ki az alábbi paramétereket a vevőtípus létrehozásához.</strong></p>
              <p>Megnevezés:</p>
              <input type="text" id="AlertBox-Name-${id}" placeholder="Megnevezés" autocomplete="off">
              <p>Pénznem:</p>
              <input type="text" id="AlertBox-Currency-${id}" placeholder="Pénznem" autocomplete="off" list="currency-list">
              <br clear="all"><br>
              <button id="AlertBtnNo-${id}" style="float: right; margin-left: 15px; width: 80px;">Mégsem</button>
              <button id="AlertBtnYes-${id}" style="float: right; width: 95px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Létrehozás</button>
          `;


          const overlay = CreateAlertBox('Vevőtípus létrehozása', html);
          document.getElementById('AlertBtnYes-'+id).onclick = function () {
            CreateCustomerType(document.getElementById('AlertBox-Name-'+id).value, document.getElementById('AlertBox-Currency-'+id).value);
            CloseAlertBox(overlay);
          };
          document.getElementById('AlertBtnNo-'+id).onclick = function () {
            CloseAlertBox(overlay);
          };
        } else {
          Loading(true);
          const body = 'func=CreateCustomerType&type_name=' + encodeURIComponent(type_name).replace(/%20/g, '+') + '&currency=' + encodeURIComponent(currency).replace(/%20/g, '+');
          get_POST_information("pricing.php", body, function(text) {
            Loading(false);
            let response = JSON.parse(text);
            if (response.result == "ok") {
              LoadCustomerType();
            } else {
              GenerateAlerts("error", response.result);
            }
          }, function() {
            Loading(false);
            GenerateAlerts("error", "Hálózati hiba!");
          });
        }
      }

      var exchange = 1;
      function SelectCustomerType(type_name) {
        Loading(true);
        document.querySelectorAll('.customer-type-item').forEach(item => {
        	item.classList.remove('active');
        });

        document.getElementById(type_name + '_sidebar').classList.add('active');

        const body = 'func=OpenCustomerType&type_name=' + encodeURIComponent(type_name).replace(/%20/g, '+');
        get_POST_information("pricing.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            document.getElementById("main-content").style.display = "flex";
            var table = document.getElementById('table').getElementsByTagName('tbody')[0];
            table.innerHTML = "";

            var Currency = '';

            if (response.data[0].currency == "HUF") {
              document.getElementById('c_exchange').innerHTML = '1';
              exchange = 1;
            } else {
              document.getElementById('c_exchange').innerHTML = response.exchange;
              exchange = response.exchange;
            }
            document.getElementById('c_currency').innerHTML = response.data[0].currency;
            document.getElementById('c_exchange_table').innerHTML = response.data[0].currency;

            response.data.forEach((item, i) => {
              var newRow = table.insertRow();
              var cat_name = newRow.insertCell(0);
              var cat_price = newRow.insertCell(1);
              var cat_exchange = newRow.insertCell(2);
              var cat_create = newRow.insertCell(3);

              Currency = item.currency;

              cat_name.innerHTML = item.category_name;
              cat_price.innerHTML = `<input class="price" type="number" min="0" value="${item.price ? item.price : ''}" autocomplete="off" step="0.01" onchange="EditCategoryName('${type_name}', '${item.category_name}', this.value)"> <span style="color: var(--panelcolor); margin-left: 10px;">${item.currency}</span>`;

              let rounded = Math.round((item.price ? item.price : 1) * exchange * 100) / 100;
              cat_exchange.innerHTML = `${rounded.toFixed(rounded % 1 === 0 ? 0 : 2)} <span style="color: var(--panelcolor); opacity: 0.8; font-size: 14px;">HUF</span>`;

              cat_create.innerHTML = `<button onclick="DisableCategory(${item.ct_id}, '${item.category_name}', '${type_name}')" style="width:36px; background: red; color: #f5f5f5; opacity: 0.6;">-</button>`;
              cat_create.style.width = "36px";
            });

            if (Currency == '') {
              LoadCustomerType();
            }

            var newRow = table.insertRow();
            var cat_name = newRow.insertCell(0);
            var cat_price = newRow.insertCell(1);
            var cat_exchange = newRow.insertCell(2);
            var cat_create = newRow.insertCell(3);

            cat_name.innerHTML = `<input type="text" id="new_category_name" autocomplete="off" placeholder="Megnevezés...">`;
            cat_price.innerHTML = `<input class="price" type="number" min="0" value="" autocomplete="off" step="0.01"> <span style="color: var(--panelcolor); margin-left: 10px;">${Currency}</span>`;

            cat_create.innerHTML = `<button onclick="EditCategoryName('${type_name}')" style="width:36px; background: var(--panelcolor); color: var(--bgcolor);">+</button>`;
            cat_create.style.width = "36px";

          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });

      }

      function EditCategoryName(type_name, category_name = document.getElementById("new_category_name").value, price) {
        Loading(true);
        const body = 'func=EditCategoryName&type_name=' + encodeURIComponent(type_name).replace(/%20/g, '+') + '&category_name=' + encodeURIComponent(category_name).replace(/%20/g, '+') + '&price=' + price;
        get_POST_information("pricing.php", body, function(text) {
          Loading(false);
          let response = JSON.parse(text);
          if (response.result == "ok") {
            SelectCustomerType(type_name);
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      }

      function DisableCategory(ct_id, cat_name, type_name, confirm = false) {
        if (confirm) {
          Loading();
          const body = 'func=DisableCategory&ct_id=' + ct_id;
          get_POST_information("pricing.php", body, function(text) {
            Loading(false);
            let response = JSON.parse(text);
            if (response.result == "ok") {
              GenerateAlerts("success", "Sikeresen törölte az árkategóriát");
              SelectCustomerType(type_name);
            } else {
              GenerateAlerts("error", response.result);
            }
          }, function() {
            Loading(false);
            GenerateAlerts("error", "Hálózati hiba!");
          });
        } else {
          var html = `
          <p><b>Biztos benne, hogy törölni szeretné a(z) '${cat_name}' árkategóriát?</b></p>
          <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 60px;">Nem</button>
          <button id="AlertBtnYes" style="float: right; width: 60px; background: red; color: #f5f5f5; border: unset;">Törlés</button>
          `;
          const overlay = CreateAlertBox('Árkategória törlés', html);
          document.getElementById('AlertBtnYes').onclick = function () { DisableCategory(ct_id, cat_name, type_name, true); CloseAlertBox(overlay); };
          document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); };
          return;
        }
      }
    </script>
  </body>
</html>
