<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.1.2                 # ||
|| # ----------------------------------------- # ||
|| # Copyright 2023 JAKWEB All Rights Reserved # ||
|| ############################################# ||
\*===============================================*/

// Check if the file is accessed only via index.php if not stop the script from running
if (!defined('JAK_PREVENT_ACCESS')) die('No direct access!');

use YooKassa\Client;

if (JAK_BILLING_MODE != 0) {
  // Include the payment class
  include_once(APP_PATH.'class/class.payment.php');

  // Now we finally initate the payment module
  $JAK_payment = new JAK_payment();
}

// Get the important database table
$jaktable1 = 'support_tickets';
$jaktable2 = 'clients';
$jaktable3 = 'departments';
$jaktable4 = 'support_departments';
$jaktable5 = 'faq_categories';
$jaktable6 = 'billing_packages';
$jaktable7 = 'envato_codes';
$jaktable8 = 'envato_products';
$jaktable9 = 'cms_pages';

$jkp = "";
$errors = $errorsp = $errorsreg = array();

// Valid Agent
$valid_agent = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);

// Now do the dirty work with the post vars
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $jkp = $_POST;

    // Rating the ticket
  if (!empty($jkp['action']) && $jkp['action'] == 'support_rating') {

    if (isset($page2) && isset($page3) && is_numeric($page2) && is_numeric($page3) && $jakdb->has($jaktable1, ["AND" => ["id" => $page2, "opid" => $_SESSION['opid'], "initiated" => $page3, "reminder" => 2]])) {

      $row = $jakdb->get($jaktable1, ["clientid", "initiated", "ended"], ["id" => $page2]);

      // Sanitzise input
      $name = filter_var($jkp['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
      $email = filter_var($jkp['email'], FILTER_SANITIZE_EMAIL);
      $message = filter_var($jkp['message'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);

      // Calculate support timet
      $total_supporttime = $row['ended'] - $row['initiated'];

      $jakdb->insert("ticket_rating", ["opid" => $_SESSION['opid'],
        "ticketid" => $page2,
        "clientid" => $row["clientid"],
        "vote" => $jkp["fbvote"],
        "name" => $name,
        "email" => $email,
        "comment" => $message,
        "support_time" => $total_supporttime,
        "time" => $jakdb->raw("NOW()")]);

      // Update the table so it cannot be rated again
      $jakdb->update($jaktable1, ["reminder" => 3], ["AND" => ["id" => $page2, "opid" => $_SESSION['opid']]]);

      // Finally forward to the client area
      $_SESSION["successmsg"] = $jkl['hd71'];
      jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

    } else {
      $_SESSION["infomsg"] = $jkl['not'];
      jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));
    }

  }

    // Login IN
  elseif (!empty($jkp['action']) && $jkp['action'] == 'login') {

    // recaptcha check
    $recaptcha = false;
    // ReCaptcha Verify if key exist.
    if (!empty(JAK_RECAP_CLIENT) && !empty(JAK_RECAP_SERVER)) {
      $rcurl = 'https://www.google.com/recaptcha/api/siteverify';
      $rcdata = array(
        'secret' => JAK_RECAP_SERVER,
        'response' => $_POST["g-recaptcha-response"]
      );
      $rcoptions = array(
        'http' => array (
          'method' => 'POST',
          'content' => http_build_query($rcdata)
        )
      );
      $rccontext  = stream_context_create($rcoptions);
      $rcverify = file_get_contents($rcurl, false, $rccontext);
      $captcha_success = json_decode($rcverify);
      if ($captcha_success->success == false) {
        $errors['recaptcha'] = $jkl['e12'].'<br>';
        $recaptcha = true;
        $client_check = false;
      }
    }
    
    if (!$recaptcha) {
      $lcookies = false;
      $email = filter_var($jkp['email'], FILTER_SANITIZE_EMAIL);
      $userpass = $jkp['password'];
      if (isset($jkp['lcookies'])) $lcookies = $jkp['lcookies'];

        // Security fix
      $valid_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);

        // Write the log file each time someone tries to login before
      JAK_base::jakWhatslog('', $_SESSION['opid'], 0, 0, 4, 0, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $email, $_SERVER['REQUEST_URI'], $valid_ip, $valid_agent);

      // Check that everything is OK
      $client_check = $jakclientlogin->jakCheckuserdata($email, $userpass);

    }

    if ($client_check == true) {

        // Now login in the user
      $jakclientlogin->jakLogin($email, $userpass, $lcookies);

          // Write the log file each time someone login after to show success
      JAK_base::jakWhatslog('', $_SESSION['opid'], 0, $client_check, 5, 0, '', $email, '', $valid_ip, '');

          // Unset the recover message
      if (isset($_SESSION['password_recover'])) unset($_SESSION['password_recover']);

      if (isset($_SESSION['LCRedirect'])) {
        jak_redirect($_SESSION['LCRedirect']);
      } else {
        jak_redirect(BASE_URL);
      }

    } else {
      if (isset($errors['recaptcha'])) {
        $errorsl = $errors;
      } else {
        $ErrLogin = $jkl['l'];
      }


    }
  }

  // Forgot password
  elseif (!empty($jkp['action']) && $jkp['action'] == 'forgot-password') {

    if (isset($jkp['lsE']) && ($jkp['lsE'] == '' || !filter_var($jkp['lsE'], FILTER_VALIDATE_EMAIL))) {
      $errors['e'] = $jkl['e1'];
    }

     // ReCaptcha Verify if key exist.
    if (!empty(JAK_RECAP_CLIENT) && !empty(JAK_RECAP_SERVER)) {
      $rcurl = 'https://www.google.com/recaptcha/api/siteverify';
      $rcdata = array(
        'secret' => JAK_RECAP_SERVER,
        'response' => $_POST["g-recaptcha-response"]
      );
      $rcoptions = array(
        'http' => array (
          'method' => 'POST',
          'content' => http_build_query($rcdata)
        )
      );
      $rccontext  = stream_context_create($rcoptions);
      $rcverify = file_get_contents($rcurl, false, $rccontext);
      $captcha_success = json_decode($rcverify);
      if ($captcha_success->success == false) {
        $errors['recaptcha'] = $jkl['e12'].'<br>';
      }
    }

     // transform user email
    $femail = filter_var($jkp['lsE'], FILTER_SANITIZE_EMAIL);
    $fwhen = time();

     // Check if this user exist
    $client_check = $jakclientlogin->jakForgotpassword($femail, $fwhen);

    if (!$client_check) {
      $errors['e'] = $jkl['e1'];
    }

    if (count($errors) == 0) {

      // Get user details
          $oname = $jakdb->get($jaktable2, ["id", "name"], ["AND" => ["email" => $femail, "access" => 1]]);

      // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
          if (jak_send_email($femail, "", "", JAK_TITLE.' - '.$jkl['hd21'], sprintf($jkl['hd28'], $oname["name"], '<a href="'.JAK_rewrite::jakParseurl('forgot-password', $fwhen).'">'.JAK_rewrite::jakParseurl('forgot-password', $fwhen).'</a>', JAK_TITLE), "")) {

             // Write the log file each time someone login after to show success
             JAK_base::jakWhatslog('', $_SESSION['opid'], 0, $oname["id"], 9, 0, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $femail, $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

             $_SESSION["infomsg"] = $jkl["hd29"];
             jak_redirect($_SESSION['LCRedirect']);
           }

       } else {
         $errorfp = $errors;
       }
  }

  // Register
  elseif (!empty($jkp['action']) && $jkp['action'] == 'register') {

     if (empty($jkp["reg_name"])) {
       $errors['e'] = $jkl['e'].'<br>';
     }

     if (empty($jkp["reg_email"]) || !filter_var($jkp["reg_email"], FILTER_VALIDATE_EMAIL)) {
       $errors['e1'] = $jkl['e1'].'<br>';
     }

     if (jak_field_not_exist(strtolower($jkp['reg_email']), $jaktable2, "email")) {
       $errors['e1'] = $jkl['hd35'].'<br>';
     }

    // ReCaptcha Verify if key exist.
     if (!empty(JAK_RECAP_CLIENT) && !empty(JAK_RECAP_SERVER)) {
       $rcurl = 'https://www.google.com/recaptcha/api/siteverify';
       $rcdata = array(
         'secret' => JAK_RECAP_SERVER,
         'response' => $_POST["g-recaptcha-response"]
       );
       $rcoptions = array(
         'http' => array (
           'method' => 'POST',
           'content' => http_build_query($rcdata)
         )
       );
       $rccontext  = stream_context_create($rcoptions);
       $rcverify = file_get_contents($rcurl, false, $rccontext);
       $captcha_success = json_decode($rcverify);
       if ($captcha_success->success == false) {
         $errors['recaptcha'] = $jkl['e12'].'<br>';
       }
     }

    // And we check the custom fields
     $formfields = $jakdb->select('customfields', ["title", "val_slug"], ["AND" => ["fieldlocation" => 1, "mandatory" => 1, "onregister" => 1]]);
     if (isset($formfields) && !empty($formfields)) {
       foreach ($formfields as $v) {
         if (!isset($jkp[$v["val_slug"]]) || empty($jkp[$v["val_slug"]])) {
           $errors[$v["val_slug"]] = sprintf($jkl['hd31'], $v["title"]).'<br>';
         }
       }
     }

     if (count($errors) == 0) {

      // create new password
       $password = jak_password_creator();
       $passcrypt = hash_hmac('sha256', $password, DB_PASS_HASH);

       $jakdb->insert($jaktable2, ["opid" => $_SESSION['opid'],
         "chat_dep" => JAK_STANDARD_CHAT_DEP,
         "support_dep" => JAK_STANDARD_SUPPORT_DEP,
         "faq_cat" => JAK_STANDARD_FAQ_CAT,
         "name" => filter_var($jkp["reg_name"], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
         "email" => $jkp['reg_email'],
         "password" => $passcrypt,
         "canupload" => 1,
         "access" => 1,
         "time" => $jakdb->raw("NOW()")]);

       $lastid = $jakdb->id();

       if (!$lastid) {
         $_SESSION["errormsg"] = $jkl['not'];
         jak_redirect($_SESSION['LCRedirect']);
       } else {

         $newuserpath = APP_PATH.JAK_FILES_DIRECTORY.'/clients/'.$lastid;

         if (!is_dir($newuserpath)) {
           mkdir($newuserpath, 0755);
           copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $newuserpath."/index.html");
         }

         // And we complete the custom fields jak_save_custom_fields($opid, $clientid, $ticketid, $contactid, $jkp, $fieldloc)
          jak_save_custom_fields($_SESSION['opid'], $lastid, 0, 0, $jkp, 1);

        // Get the email template
         $nlhtml = file_get_contents(APP_PATH.'template/'.JAK_FRONT_TEMPLATE.'/email/index.html');

        // Change fake vars into real ones.
         if (!empty($HD_ANSWERS) && is_array($HD_ANSWERS)) foreach ($HD_ANSWERS as $v) {
           if ($v["msgtype"] == 14 && $v["lang"] == JAK_LANG) {
             $phold = array('{url}', '{title}', '{cname}', '{cemail}', '{cpassword}', '{email}');
             $replace   = array(BASE_URL, JAK_TITLE, $jkp['reg_name'], $jkp['reg_email'], $password, JAK_EMAIL);
             $regtext = str_replace($phold, $replace, $v["message"]);
             break;
           }
         }

        // Change fake vars into real ones.
         $cssAtt = array('{emailcontent}', '{weburl}', '{title}', '{emailtpllogo}', '{emailtplcopy}');
         $cssUrl   = array($regtext, BASE_URL, JAK_TITLE, JAK_EMAILTPLLOGO, JAK_EMAILTPLCOPY);
         $nlcontent = str_replace($cssAtt, $cssUrl, $nlhtml);

         $body = str_ireplace("[\]", "", $nlcontent);

         // Ok, we send the email // email address, cc email address, reply to, subject, message, attachment
            if (jak_send_email($jkp['reg_email'], "", "", JAK_TITLE.' - '.$jkl['hd33'], $body, "")) $_SESSION["infomsg"] = $jkl['hd32'];

        $_SESSION["successmsg"] = $jkl["hd34"];
        jak_redirect($_SESSION['LCRedirect']);
      }

    } else {
      $errorsreg = $errors;
    }
  }

  // Save Client
  elseif (!empty($jkp['action']) && $jkp['action'] == 'save_client') {

    $updatepass = false;

    if (empty($jkp["name"])) {
      $errors['e'] = $jkl['e'].'<br>';
    }

    if (empty($jkp["email"]) || !filter_var($jkp["email"], FILTER_VALIDATE_EMAIL)) {
      $errors['e1'] = $jkl['e1'].'<br>';
    }

    if (jak_field_not_exist_id($jkp['email'], JAK_CLIENTID, $jaktable2, "email")) {
      $errors['e1'] = $jkl['hd35'].'<br>';
    }

    // And we check the custom fields
    $formfields = $jakdb->select('customfields', ["title", "val_slug"], ["AND" => ["fieldlocation" => 1, "mandatory" => 1]]);
    if (isset($formfields) && !empty($formfields)) {
      foreach ($formfields as $v) {
        if (isset($jkp[$v["val_slug"]])) {
          if (empty($jkp[$v["val_slug"]])) {
            $errors[$v["val_slug"]] = sprintf($jkl['hd31'], $v["title"]).'<br>';
          }
        }
      }
    }

    if (!empty($jkp['jak_newpassword']) || !empty($jkp['jak_cpassword'])) {    
      if ($jkp['jak_newpassword'] != $jkp['jak_cpassword']) {
        $errors['e2'] = $jkl['hd62'];
      } elseif (strlen($jkp['jak_newpassword']) <= '7') {
        $errors['e3'] = $jkl['hd63'];
      } else {
        $updatepass = true;
      }
    }

    if (isset($jkp['deleteavatar']) && $jkp['deleteavatar'] == 1) {


      // first get the target path
      $targetPathd = APP_PATH.JAK_FILES_DIRECTORY.'/clients/'.JAK_CLIENTID.'/';
      $targetPath =  str_replace("//","/",$targetPathd);

      // if old avatars exist delete it
      foreach(glob($targetPath.'*.*') as $jak_unlink){
        unlink($jak_unlink);
      }
         // Remove the directory as we do not need it anymore. (+1 for a clean system)
      rmdir($targetPath);

         // SQL update
      $jakdb->update($jaktable2, ["picture" => "/standard.jpg"], ["id" => JAK_CLIENTID]);

    }

    if (!empty($_FILES['avatar']['name'])) {

      if ($_FILES['avatar']['name'] != '') {

          $filename = $_FILES['avatar']['name']; // original filename
          // Fix explode when upload in 1.2
          $tmpf = explode(".", $filename);
          $jak_xtension = end($tmpf);
          
          if ($jak_xtension == "jpg" || $jak_xtension == "jpeg" || $jak_xtension == "png" || $jak_xtension == "gif") {

            if ($_FILES['avatar']['size'] <= 2000000) {

              list($width, $height, $type, $attr) = getimagesize($_FILES['avatar']['tmp_name']);
              $mime = image_type_to_mime_type($type);

              if (($mime == "image/jpeg") || ($mime == "image/pjpeg") || ($mime == "image/png") || ($mime == "image/gif")) {

                // first get the target path
                $targetPathd = APP_PATH.JAK_FILES_DIRECTORY.'/clients/'.JAK_CLIENTID.'/';
                $targetPath =  str_replace("//","/",$targetPathd);

                // Create the target path
                if (!is_dir($targetPath)) {
                  mkdir($targetPath, 0755);
                  copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $targetPath . "/index.html");

                }

                // if old avatars exist delete it
                foreach(glob($targetPath.'*.*') as $jak_unlink){
                  unlink($jak_unlink);
                  copy(APP_PATH.JAK_FILES_DIRECTORY."/index.html", $targetPath . "/index.html");
                }

                $tempFile = $_FILES['avatar']['tmp_name'];
                $origName = substr($_FILES['avatar']['name'], 0, -4);
                $name_space = strtolower($_FILES['avatar']['name']);
                $middle_name = str_replace(" ", "_", $name_space);
                $middle_name = str_replace(".jpeg", ".jpg", $name_space);
                $glnrrand = rand(10, 99);
                $bigPhoto = str_replace(".", "_" . $glnrrand . ".", $middle_name);
                $smallPhoto = str_replace(".", "_t.", $bigPhoto);

                $targetFile =  str_replace('//','/',$targetPath) . $bigPhoto;
                $origPath = '/clients/'.JAK_CLIENTID.'/';
                $dbSmall = $origPath.$smallPhoto;

                require_once APP_PATH.'include/functions_thumb.php';
                // Move file and create thumb     
                move_uploaded_file($tempFile,$targetFile);

                create_thumbnail($targetPath, $targetFile, $smallPhoto, JAK_USERAVATWIDTH, JAK_USERAVATHEIGHT, 80);

                // SQL update
                $jakdb->update($jaktable2, ["picture" => $dbSmall], ["id" => JAK_CLIENTID]);

              } else {
                $errors['e4'] = $jkl['hd60'].'<br>';
              }

            } else {
              $errors['e4'] = $jkl['hd60'].'<br>';
            }

          } else {
            $errors['e4'] = $jkl['hd60'].'<br>';
          }
          
        } else {
          $errors['e4'] = $jkl['hd60'].'<br>';
        }
        
    }

    if (count($errors) == 0) {

      $result = $jakdb->update($jaktable2, [ 
        "name" => filter_var($jkp["name"], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
        "email" => $jkp['email'],
        "language" => $jkp['jak_lang']], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

      if (!$result) {
        $_SESSION["errormsg"] = $jkl['not'];
        jak_redirect($_SESSION['LCRedirect']);
      } else {

        // Finally we update the password
        if ($updatepass) $jakdb->update($jaktable2, ["password" => hash_hmac('sha256', $jkp['jak_newpassword'], DB_PASS_HASH)], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // And we complete the custom fields jak_save_custom_fields($opid, $clientid, $ticketid, $contactid, $jkp, $fieldloc)
          jak_save_custom_fields($_SESSION['opid'], JAK_CLIENTID, 0, 0, $jkp, 1);

        $_SESSION["successmsg"] = $jkl["hd61"];
        jak_redirect($_SESSION['LCRedirect']);

      }

    } else {

      $_SESSION["errormsg"] = $jkl["e20"];
      $errorsp = $errors;
    }

  } elseif (!empty($jkp['action']) && $jkp['action'] == 'payment') {

    // Get the package
    $pack = $jakdb->get("billing_packages", ["id", "title", "content", "previmg", "credits", "paidtill", "chat_dep", "support_dep", "faq_cat", "amount", "currency"], ["AND" => ["id" => $jkp["pid"], "opid" => $_SESSION['opid'], "active" => 1],
        "ORDER" => ["dorder" => "DESC"]]);

    // Now let's get the current subscription
    $subs = $jakdb->get("subscriptions_client", ["id", "paidhow", "package", "subscribed", "planid", "paidtill"], ["AND" => ["opid" => $_SESSION['opid'], "clientid" => JAK_CLIENTID, "active" => 1]]);

    if (isset($pack) && isset($pack["id"])) {

    // Let's check if we have a subscription
    $subscribed = 0;
    $planid = $pack["title"].'-'.$pack["id"];
    if ($_POST["subscribe"] == 1) {

      // We subscribing
      $subscribed = 1;

      // Ok we need to figure out the intervals for charging the customer
      $intervalc = 1;
      $intervalm = "month";
      if ($pack['paidtill'] == "1 WEEK") {
        $intervalm = "week";
      } elseif ($pack['paidtill'] == "1 MONTH") {
        $intervalm = "month";
      } elseif ($pack['paidtill'] == "6 MONTHS") {
        $intervalc = 6;
        $intervalm = "month";
      } elseif ($pack['paidtill'] == "1 YEAR") {
        $intervalm = "year";
      }

      // plan name
      $planid = $pack["title"].'-PackageID:'.$pack["id"].'-'.$intervalc.'-'.$intervalm;

    }

    // We have now a downgrade but we are not allowed to have a downgrade or we have a payment in a different currency
    if (isset($subs["subscribed"]) && $subs["subscribed"] == 1 && !empty($subs["planid"])) {

      if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
        header('Cache-Control: no-cache');
        die(json_encode(array("status" => 0, "infomsg" => $jkl["hd173"])));
      } else {
        // redirect back to home
        $_SESSION["errormsg"] = $jkl["hd173"];
        jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));
      }

    }

    // Ok, we have no errors we need to create a payidnow for checking that the payment was legal
    $payidnow = base64_url_encode(JAK_CLIENTID.':#:'.$pack["id"].':#:'.$jkp["paidhow"].':#:'.$jkp["amount"].':#:'.microtime().':#:'.$planid.':#:'.$subscribed);
    // We will need to enter the information into a temporary database
    $jakdb->insert("payment_security_client", ["opid" => $opcacheid, "clientid" => JAK_CLIENTID, "payidnow" => $payidnow, "created" => $jakdb->raw("NOW()")]);

    switch ($jkp["paidhow"]) {
      case 'stripe':
        // code...

        if (isset($subscribed) && $subscribed == 1) {

          // Now we need to either get the plan id from the database or create one
          if (isset($planid) && $jakdb->has("payment_plans_client", ["AND" => ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"]]])) {

            $subscription_id = $jakdb->get("payment_plans_client", "planid", ["AND" => ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"]]]);

          } else {

            $subscription_id = $JAK_payment->JAK_pay("stripe", $jkp["amount"], $pack["currency"], $intervalm, $planid, "recurring", "create_plan", $intervalc, "", JAK_STRIPE_SECRET_KEY, JAK_STRIPE_PUBLISH_KEY, JAK_SANDBOX_MODE);

            if (isset($subscription_id) && !empty($subscription_id)) {

              // We insert the subscription id for later use
              $jakdb->insert("payment_plans_client", ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"], "planid" => $subscription_id, "created" => $jakdb->raw("NOW()")]);

            } else {

              // redirect back to home
              $_SESSION["errormsg"] = $jkl["hd111"];
              jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

            }
          }

          // We have a subscription plan
          $JAK_payment->JAK_pay("stripe", "", "", $subscription_id, "", "recurring", "buy", JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow, $subscription_id), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow), JAK_STRIPE_SECRET_KEY, JAK_STRIPE_PUBLISH_KEY, JAK_SANDBOX_MODE);

        } else {

          // Single payment, make sure there is no subscription
          $JAK_payment->JAK_pay("stripe", $jkp["amount"], $pack["currency"], $pack["id"], $planid, "single", "", JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow), JAK_STRIPE_SECRET_KEY, JAK_STRIPE_PUBLISH_KEY, JAK_SANDBOX_MODE);

        }
        
        break;

      case 'paypal':
        // code...

        if (isset($subscribed) && $subscribed == 1) {

          // Now we need to either get the plan id from the database or create one
          if (isset($planid) && $jakdb->has("payment_plans_client", ["AND" => ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"]]])) {

            $subscription_id = $jakdb->get("payment_plans_client", "planid", ["AND" => ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"]]]);

          } else {

            $subscription_id = $JAK_payment->JAK_pay("paypal", $jkp["amount"], $pack["currency"], "PackageID-".$pack["id"], $planid, "recurring", "create_plan", $intervalm, $intervalc, JAK_PAYPAL_CLIENT, JAK_PAYPAL_SECRET, JAK_SANDBOX_MODE);

            if (isset($subscription_id) && !empty($subscription_id)) {

              // We insert the subscription id for later use
              $jakdb->insert("payment_plans_client", ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"], "planid" => $subscription_id, "created" => $jakdb->raw("NOW()")]);

            } else {

              // redirect back to home
              $_SESSION["errormsg"] = $jkl["hd111"];
              jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

            }
          }

          // We have a subscription plan
          $subscribeToken = $JAK_payment->JAK_pay("paypal", $jkp["amount"], $pack["currency"], $subscription_id, "", "recurring", "buy", JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow, $subscription_id), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow), JAK_PAYPAL_CLIENT, JAK_PAYPAL_SECRET, JAK_SANDBOX_MODE);

          if ($subscribeToken) {
            jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow, $subscription_id, $subscribeToken));
          } else {
            jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow));
          }

        } else {

          // Single payment, make sure there is no subscription
          $JAK_payment->JAK_pay("paypal", $jkp["amount"], $pack["currency"], $pack["id"], $planid, "single", "", JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow), JAK_PAYPAL_CLIENT, JAK_PAYPAL_SECRET, JAK_SANDBOX_MODE);

        }

        break;

      case 'verifone':
        // code...

        $_SESSION["infomsg"] = $jkl["hd174"];
        jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

        // More infos
        /* $usrinfo = array(
              'name'=>$jakuser->getVar("name"),
              'email'=> $jakuser->getVar("email")
          ); */

        break;

      case 'authorize.net':
        // code...

          $_SESSION["infomsg"] = $jkl["hd174"];
          jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

        break;

      case 'yoomoney':
        // code...

        if (isset($subscribed) && $subscribed == 1) {

          // YooKassa is strange with handling payments we just run it
          $subscription_id = $JAK_payment->JAK_pay("yoomoney", $jkp["amount"], $pack["currency"], "PackageID-".$pack["id"], $planid, "recurring", "buy", JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow), "", JAK_YOOKASSA_ID, JAK_YOOKASSA_SECRET, JAK_SANDBOX_MODE);


        } else {

          // Single payment, make sure there is no subscription
          $JAK_payment->JAK_pay("yoomoney", $jkp["amount"], $pack["currency"], "", $planid, "single", "", JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow), JAK_YOOKASSA_ID, JAK_YOOKASSA_SECRET, JAK_SANDBOX_MODE);

        }

        break;

      case 'paystack':
        // code...

        if (isset($subscribed) && $subscribed == 1) {

          // Now we need to either get the plan id from the database or create one
          if (isset($planid) && $jakdb->has("payment_plans_client", ["AND" => ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"]]])) {

            $subscription_id = $jakdb->get("payment_plans_client", "planid", ["AND" => ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packegid" => $pack["id"]]]);

          } else {

            $subscription_id = $JAK_payment->JAK_pay("paystack", $jkp["amount"], $pack["currency"], "PackageID-".$pack["id"], $planid, "create_plan", "", $intervalm, $intervalc, JAK_PAYSTACK_SECRET, "", JAK_SANDBOX_MODE);

            if (isset($subscription_id) && !empty($subscription_id)) {

              // We insert the subscription id for later use
              $jakdb->insert("payment_plans_client", ["opid" => $_SESSION['opid'], "paidhow" => $jkp["paidhow"], "amount" => $jkp["amount"], "currency" => $pack["currency"], "interval" => $intervalm, "interval_count" => $intervalc, "packageid" => $pack["id"], "planid" => $subscription_id, "created" => $jakdb->raw("NOW()")]);

            } else {

              // redirect back to home
              $_SESSION["errormsg"] = $jkl["hd111"];
              jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

            }
          }

          // We have a subscription plan
          $subscribeToken = $JAK_payment->JAK_pay("paystack", $jkp["amount"], $pack["currency"], $subscription_id, "", "buy_plan", $jakuser->getVar("email"), "", 
            "", JAK_PAYSTACK_SECRET, "", JAK_SANDBOX_MODE);

          if ($subscribeToken) {
            jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow, $subscription_id, $subscribeToken));
          } else {
            jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow));
          }

        } else {

          // Single payment, make sure there is no subscription
          $JAK_payment->JAK_pay("paystack", $jkp["amount"], $pack["currency"], $pack["id"], $planid, "single", $jakuser->getVar("email"), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'success', $payidnow), JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'cancel', $payidnow), JAK_PAYSTACK_SECRET, "", JAK_SANDBOX_MODE);

        }

        break;
      }

    } else {

      // redirect back to home
      $_SESSION["errormsg"] = $jkl["hd111"];
      jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

    }

  }

}

// Rate the ticket
if ($page1 == "rt") {

  if (isset($page2) && isset($page3) && is_numeric($page2) && is_numeric($page3) && $jakdb->has($jaktable1, ["AND" => ["id" => $page2, "opid" => $_SESSION['opid'], "initiated" => $page3, "reminder" => 2]])) {

    $row = $jakdb->get($jaktable1, ["id", "name", "email", "subject"], ["AND" => ["id" => $page2, "opid" => $_SESSION['opid']]]);

    // Include the javascript file for results
    $js_file_footer = 'js_rating.php';

    // Load the template
    include_once APP_PATH.'template/'.JAK_FRONT_TEMPLATE.'/tplblocks/rateticket.php';

    exit();

  } else {
    $_SESSION["infomsg"] = $jkl['not'];
    jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));
  }

}

// When client/user is logged in
if (JAK_USERISLOGGED) {

  // We edit some client details
  if ($page1 == "edit") {

    // Get the data
    $JAK_FORM_DATA = jak_get_data(JAK_CLIENTID, $_SESSION['opid'], $jaktable2);

    // Call the settings function
    $lang_files = $jakdb->select($jaktable9, "lang", ["GROUP" => "lang"]);

    // Get the custom fields jak_get_custom_fields($location, $opid, $depid, $clientid, $ticketid, $contactid, $lang, $readonly, $admin, $table, $registerform, $errors = NULL)
    $custom_fields = jak_get_custom_fields(1, $_SESSION['opid'], 0, JAK_CLIENTID, 0, 0, $JAK_FORM_DATA["language"], false, false, false, false, $errorsp);

    // Get the customer name
    $JAK_FORM_DATA["title"] = $JAK_FORM_DATA["name"];

    // Load the template
    include_once APP_PATH.'template/business/tplblocks/clientedit.php';

  } elseif ($page1 == "envato") {

    if (JAK_BILLING_MODE == 3) {

      if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == "add_license") {

        // If you took $code from user input it's a good idea to trim it
        $code = trim($_POST["purchase_code"]);

          // Make sure the code is valid before sending it to Envato
        if (!preg_match("/^(\w{8})-((\w{4})-){3}(\w{12})$/", $code)) {
          $errors['e'] = $jkl['e21'];
        }

        if (count($errors) == 0) {

            // Verify the key
          $purchase_data = verify_envato_purchase_code($code);

          if (isset($purchase_data['item']['name'])) {

            // We have a valid purchase is it also registered in the system
            if ($jakdb->has($jaktable8, ["envato_item_id" => $purchase_data['item']['id']])) {

              // Great now let's have a final check if the license is already registered
              if (!$jakdb->has($jaktable7, ["purchase_code" => $code])) {

                // Ok, all seems to be fine, let's add the code
                $result = $jakdb->insert($jaktable7, ["opid" => $_SESSION['opid'],
                  "clientid" => JAK_CLIENTID,
                  "productid" => $purchase_data['item']['id'],
                  "purchase_name" => $purchase_data['buyer'],
                  "purchase_code" => $code,
                  "purchased" => $purchase_data['sold_at'],
                  "support_expires" => $purchase_data['supported_until'],
                  "created" => $jakdb->raw("NOW()")]);

                $lastid = $jakdb->id();

                // Now we will update the client table for the support expire if older
                if ($jakdb->has($jaktable2, ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid'], "support_until[<]" => $purchase_data['supported_until']]])) {

                  $jakdb->update($jaktable2, ["support_until" => $purchase_data['supported_until']], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);
                }

                // Write the log file each time someone login after to show success
                     JAK_base::jakWhatslog('', $_SESSION['opid'], 0, JAK_CLIENTID, 103, $lastid, (isset($_COOKIE['WIOgeoData']) ? $_COOKIE['WIOgeoData'] : ''), $jakclient->getVar("email"), $_SERVER['REQUEST_URI'], $ipa, $valid_agent);

                     $_SESSION["infomsg"] = $jkl["hd152"];
                     jak_redirect($_SESSION['LCRedirect']);

              } else {
                $errors['e2'] = $jkl['e24'];
              }

            } else {
              $errors['e2'] = $jkl['e23'];
            }

          } else {
            $errors['e1'] = $jkl['e22'];
          }

        }

      }

      // Load the registered licenses
      $allLics = $jakdb->select($jaktable7, ["[>]".$jaktable8 => ["productid" => "envato_item_id"]], ["envato_codes.id", "envato_codes.purchase_name", "envato_codes.purchase_code", "envato_codes.purchased", "envato_codes.support_expires", "envato_products.product_name"], ["AND" => ["envato_codes.opid" => $_SESSION['opid'], "envato_codes.clientid" => JAK_CLIENTID], "ORDER" => ["envato_codes.support_expires" => "ASC"]]);

      // Load the template
      include_once APP_PATH.'template/business/tplblocks/envato.php';

      // Envato Mode is turned off, nothing to do here
    } else {
      jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));
    }

  } elseif (isset($page1) && $page1 == "success" && isset($page2)) {

  // Happy days Payment has been succesful and no one has cheated
  $page2d = base64_url_decode($page2);

  // clientid, packageid, paidhow, amount, time, planid (title, packageid, interval, week, month, year), subscribed
  $custom = explode(":#:", $page2d);

  // Reset
  $subscription_id = $subscribe_id = $subscribeToken = 0;

  // Now let's check if we are still on track
  if (isset($custom) && $custom[0] == JAK_CLIENTID && $jakdb->has("payment_security_client", ["AND" => ["payidnow" => $page2, "success" => 0]])) {

    // Update the payment security
    if (isset($_GET["session_id"]) && !empty($_GET["session_id"])) {
      $jakdb->update("payment_security_client", ["subscribe_id" => $_GET["session_id"]], ["payidnow" => $page2]);
         $subscribe_id = $_GET["session_id"];
         $subscribeToken = $subscribe_id;
    }

    // We have the subscription id in the URL
    if (isset($page3) && !empty($page3)) {
        $subscription_id = $jakdb->get("payment_plans_client", "id", ["planid" => $page3]);
      }

      // Paystack needs a emailToken
      if (isset($page4) && !empty($page4)) {
        $subscribeToken = $page4;
        if (!isset($_GET["session_id"])) {
          $jakdb->update("payment_security_client", ["subscribe_id" => $subscribeToken], ["payidnow" => $page2]);
        }
      }

    $jakdb->update("payment_security_client", ["success" => 1], ["payidnow" => $page2]);

    // Get the package
    $pack = $jakdb->get("billing_packages", ["id", "title", "content", "previmg", "credits", "paidtill", "chat_dep", "support_dep", "faq_cat", "amount", "currency"], ["AND" => ["id" => $custom[1], "opid" => $_SESSION['opid'], "active" => 1],
      "ORDER" => ["dorder" => "DESC"]]);

    // We will need to check if the user has paid
    if (isset($custom[2]) && $custom[2] == "yoomoney" && isset($_SESSION["yoomoney"])) {

      // Now we need to check if the payment has been paid.
      $yooclient = new Client();
            $yooclient->setAuth($paga["secretkey_one"], $paga["secretkey_two"]);
      $yoopayment = $yooclient->getPaymentInfo($_SESSION["yoomoney"]);

      if (isset($yoopayment->_status) && $yoopayment->_status == "succeeded" && isset($yoopayment->_paid) && $yoopayment->_paid == true) {


      } else {

        $_SESSION["errormsg"] = $jkl["hd111"];
          jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

      }

    }

    $jakdb->insert("payment_ipn", ["opid" => $_SESSION['opid'],
            "clientid" => JAK_CLIENTID,
            "status" => "success",
            "amount" => $custom[3],
            "currency" => $pack["currency"],
            "txn_id" => $page2,
            "receiver_email" => JAK_EMAIL,
            "payer_email" => $jakclient->getVar("email"),
            "paid_with" =>$custom[2],
            "time" => $jakdb->raw("NOW()")]);

    // check that txn_id has not been previously processed
        $onepay = $jakdb->count("payment_ipn", ["txn_id" => $page2]);

        // Current time
        $timenow = time();

        if ($onepay == 1) {

          // We have Yoomoney we need to do some extra stuff
      if (isset($custom[2]) && $custom[2] == "yoomoney" && isset($_SESSION["yoomoney"])) {

        // We insert the subscription id for later use
        if (isset($custom[6]) && $custom[6] == 1) {

          $custom1 = explode("-", $custom[5]);

          $jakdb->insert("payment_plans_client", ["opid" => $_SESSION['opid'], "packageid" => $pack['id'], "paidhow" => $custom[2], "amount" => $custom[3], "currency" => $pack["currency"], "interval" => $custom1[3], "interval_count" => $custom1[2], "planid" => $_SESSION["yoomoney"], "created" => $jakdb->raw("NOW()")]);

          // And set the token for charging the customer again
          $subscribeToken = $_SESSION["yoomoney"];
          $jakdb->update("payment_security_client", ["subscribe_id" => $subscribeToken], ["payidnow" => $page2]);

        }

        // Unset the session yoomoney
        unset($_SESSION["yoomoney"]);


      }

      // Credit based system
      if (JAK_BILLING_MODE == 1) {

        // Update the credits
        $jakdb->update($jaktable2, ["credits[+]" => $pack["credits"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Update the chat departments
        if ($pack["chat_dep"] != 0) $jakdb->update($jaktable2, ["chat_dep" => $pack["chat_dep"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Update the support departments
        if ($pack["support_dep"] != 0) $jakdb->update($jaktable2, ["support_dep" => $pack["support_dep"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Update the faq categories
        if ($pack["faq_cat"] != 0) $jakdb->update($jaktable2, ["faq_cat" => $pack["faq_cat"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

      // Memberschip based system
      } elseif (JAK_BILLING_MODE == 2) {

        // Get the new date
        if (strtotime($jakuser->getVar("paid_until")) > time()) {
          $paidunix = strtotime($pack["paidtill"], strtotime($jakuser->getVar("paid_until")));
        } else {
          $paidunix = strtotime($pack["paidtill"]);
        }

        // Now if we have a subscription we add 48 hours to the client table to make sure it get's not expired
        if (isset($custom[6]) && $custom[6] == 1) {
          $paidunix2 = strtotime('+2 days', $paidunix);
          $paidtill2 = date('Y-m-d H:i:s', $paidunix2);
        }

        $paidtill = date('Y-m-d H:i:s', $paidunix);

        // Update the credits
        $jakdb->update($jaktable2, ["paid_until" => $paidtill2], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Update the chat departments
        if ($pack["chat_dep"] != 0) $jakdb->update($jaktable2, ["chat_dep" => $pack["chat_dep"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Update the support departments
        if ($pack["support_dep"] != 0) $jakdb->update($jaktable2, ["support_dep" => $pack["support_dep"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Update the faq categories
        if ($pack["faq_cat"] != 0) $jakdb->update($jaktable2, ["faq_cat" => $pack["faq_cat"]], ["AND" => ["id" => JAK_CLIENTID, "opid" => $_SESSION['opid']]]);

        // Payment details insert
              $jakdb->insert("subscriptions_client", ["opid" => $_SESSION['opid'], 
                "clientid" => JAK_CLIENTID,
                "amount" => $custom[3],
                "paidhow" => $custom[2],
                "currency" => $pack["currency"],
              "package" => $pack["id"],
              "subscribed" => $custom[6],
              "planid" => $subscribeToken,
                "paidwhen" => $jakdb->raw("NOW()"),
                "paidtill" => $paidtill,
                "success" => 1,
              "active" => 1]);

      }

        }

        $_SESSION["successmsg"] = $jkl["hd177"];
    jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

  }

  $_SESSION["errormsg"] = $jkl["hd111"];
  jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

  } elseif (isset($page1) && $page1 == "cancel") {

      $_SESSION["errormsg"] = $jkl["hd111"];
      jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

  } elseif (isset($page1) && $page1 == "withdrawal") {
  // We cancel the subscription

  if (isset($page2) && isset($page3) && $page3 == JAK_CLIENTID) {

    // Now let's get the current subscription
    $subs = $jakdb->get("subscriptions_client", ["id", "paidhow", "package", "subscribed", "planid", "paidtill"], ["AND" => ["id" => $page2, "opid" => $_SESSION['opid'], "clientid" => JAK_CLIENTID]]);

    // Confirm from the main admin panel
    if (isset($subs) && !empty($subs)) {

      // Get the left days
      $datenow = new DateTime();  //current date or any date
        $paidtill = new DateTime($subs["paidtill"]);   //Future date
        $diffdates = $paidtill->diff($datenow)->format("%a");  //find difference
        $daysleft = intval($diffdates);   //rounding days

        // Canceled success?
        $subcanceled = false;

        // Go trought the payment gateways
      switch ($subs['paidhow']) {
        case 'stripe':
          // code...

          $subcanceled = $JAK_payment->JAK_pay("stripe", "", "", $subs["planid"], "", "recurring", "cancel_period_end", "", "", JAK_STRIPE_SECRET_KEY, JAK_STRIPE_PUBLISH_KEY, JAK_SANDBOX_MODE);

          break;

        case 'paypal':
          // code...

          $subcanceled = $JAK_payment->JAK_pay("paypal", "", "", $subs["planid"], "User canceled subscription.", "recurring", "cancel", "", "", JAK_PAYPAL_CLIENT, JAK_PAYPAL_SECRET, JAK_SANDBOX_MODE);

          break;

        case 'verifone':
          // code...

          $_SESSION["infomsg"] = $jkl["i78"];
          jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

          break;

        case 'authorize.net':
          // code...

          $_SESSION["infomsg"] = $jkl["i78"];
          jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

          break;

        case 'yoomoney':
          // code...

          // This is not a real cancelation as YooMoney does not charge the user automatically. We just stop charging the user by cron job.
          $subcanceled = true;

          break;

        case 'paystack':
          // code...

          $subcanceled = $JAK_payment->JAK_pay("paystack", "", "", $subs["planid"], "", "cancel_plan", "", "", "", JAK_PAYSTACK_SECRET, "", JAK_SANDBOX_MODE);

          break;
      }          

      // All safe and sound
      if ($subcanceled) {

        // Now we need to update the subscribed table
        $jakdb->update("subscriptions_client", ["subscribed" => 0, "planid" => "", "active" => 0], ["AND" => ["id" => $page2, "opid" => $_SESSION['opid'], "clientid" => JAK_CLIENTID]]);


        $_SESSION["successmsg"] = sprintf($jkl["hd175"], $daysleft);
          jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

        } else {

          $_SESSION["errormsg"] = $jkl["hd176"];
          jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

        }

    } else {

      $_SESSION["errormsg"] = $jkl["hd176"];
        jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));

    }

  } else {
    $_SESSION["errormsg"] = $jkl["hd176"];
      jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));
  }

  } else {

    // Some Resets
    $getTotal = 0;
    $allcsupport = $last5pay = $allpackages = array();

    // Let's go on with the script
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == "filter") {

      if (isset($_POST['jak_depid']) && is_numeric($_POST['jak_depid']) && $_POST['jak_depid'] != 0) {
        if (JAK_CLIENTID && ($jakclient->getVar("support_dep") == 0 || in_array($_POST['jak_depid'], explode(",", $jakclient->getVar("support_dep"))))) {
          $_SESSION["sortdepid"] = $_POST['jak_depid'];
        } elseif (JAK_USERID && ($jakuser->getVar("support_dep") == 0 || in_array($_POST['jak_depid'], explode(",", $jakuser->getVar("support_dep"))))) {
          $_SESSION["sortdepid"] = $_POST['jak_depid'];
        } else {
          if (isset($HD_SUPPORT_DEPARTMENTS) && !empty($HD_SUPPORT_DEPARTMENTS)) foreach ($HD_SUPPORT_DEPARTMENTS as $d) {
            if ($d["id"] == $_POST['jak_depid'] && $d["guesta"] == 1) {
              $_SESSION["sortdepid"] = $_POST['jak_depid'];
            }
          }
        }
        jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL, 'c', $_SESSION["sortdepid"]));
      } else {
        unset($_SESSION["sortdepid"]);
        jak_redirect(JAK_rewrite::jakParseurl(JAK_CLIENT_URL));
      }

    }

    // Get the last 5 payments
    if (JAK_CLIENTID) {

      // Let's rock with the payment module.

      // Get the last 5 payments
      $last5pay = $jakdb->select("subscriptions_client", ["[>]billing_packages" => ["package" => "id"]], ["subscriptions_client.id", "subscriptions_client.amount", "subscriptions_client.currency", "subscriptions_client.paidhow", "subscriptions_client.paidwhen", "subscriptions_client.paidtill", "subscriptions_client.subscribed", "subscriptions_client.success", "subscriptions_client.active", "billing_packages.title"], ["AND" => ["subscriptions_client.opid" => $_SESSION['opid'], "subscriptions_client.clientid" => JAK_CLIENTID],
        "ORDER" => ["subscriptions_client.paidwhen" => "DESC"],
        "LIMIT" => 5
      ]);

      // Get all packages
      $allpackages = $jakdb->select("billing_packages", ["id", "title", "content", "previmg", "credits", "paidtill", "chat_dep", "support_dep", "faq_cat", "amount", "currency"], ["AND" => ["opid" => $_SESSION['opid'], "active" => 1],
        "ORDER" => ["dorder" => "DESC"]
      ]);

      // Get the correct departments
      $dep_filter = array();
      if (JAK_CLIENTID) {
        if (isset($HD_SUPPORT_DEPARTMENTS) && !empty($HD_SUPPORT_DEPARTMENTS)) foreach ($HD_SUPPORT_DEPARTMENTS as $d) {
          if ($d["guesta"] == 1 || $jakclient->getVar("support_dep") == 0 || in_array($d["id"], explode(",", $jakclient->getVar("support_dep")))) {
            $dep_filter[] = $d;
          }
        }
      }

      // Include the javascript file for results
      $js_file_footer = 'js_dashboard.php';

      // Load the template
      include_once APP_PATH.'template/business/tplblocks/dashboard.php';

  } // End clientid

  if (JAK_USERID) {

    jak_redirect(JAK_rewrite::jakParseurl(JAK_OPERATOR_LOC, 'support'));
  }

}


// Get the stuff when user is not logged in
} else {

  // Get the custom fields jak_get_custom_fields($location, $opid, $depid, $clientid, $ticketid, $contactid, $lang, $readonly, $admin, $table, $registerform, $errors = NULL)
  $custom_fields = jak_get_custom_fields(1, $_SESSION['opid'], 0, 0, 0, 0, $BT_LANGUAGE, false, false, false, true, $errorsreg);

  // Include the javascript file for results
  $js_file_footer = 'js_client.php';

  // Load the template
  include_once APP_PATH.'template/business/tplblocks/client.php';
}
?>
