<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.0.5                 # ||
|| # ----------------------------------------- # ||
|| # Copyright 2022 JAKWEB All Rights Reserved # ||
|| ############################################# ||
\*===============================================*/

// This Cron Job should run twice a day, to make sure there is no interruption

$cron_url_orig = dirname(__file__) . DIRECTORY_SEPARATOR;
$cron_url = str_replace("cron".DIRECTORY_SEPARATOR, "", $cron_url_orig);

if (!file_exists($cron_url.'include/db.php')) die('cron/[cron.php] db.php not exist');
require_once $cron_url.'include/db.php';

if (!file_exists($cron_url.'class/class.db.php')) die('cron/[cron.php] class.db.php not exist');
require_once $cron_url.'class/class.db.php';

if (!file_exists($cron_url.'class/class.jakbase.php')) die('cron/[cron.php] class.jakbase.php not exist');
require_once $cron_url.'class/class.jakbase.php';

// Include the payment class
include_once($cron_url.'class/class.payment.php');

use YooKassa\Client;

use JAKWEB\JAKsql;

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

// Database connection
$jakdb = new JAKsql([
    // required
    'database_type' => JAKDB_DBTYPE,
    'database_name' => JAKDB_NAME,
    'server' => JAKDB_HOST,
    'username' => JAKDB_USER,
    'password' => JAKDB_PASS,
    'charset' => 'utf8',
    'port' => JAKDB_PORT,
    'prefix' => JAKDB_PREFIX,
 
    // [optional] driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
    'option' => [PDO::ATTR_CASE => PDO::CASE_NATURAL]
    ]);

// Check if we have a database connection
if ($jakdb) {

  // We start with the clients to make sure there service does not get interrupted
  $sc = $jakdb->select("subscriptions_client", ["id", "opid", "clientid", "amount", "currency", "paidhow", "subscribed", "package", "planid", "paidtill", "gatewaycheck"], ["AND" => ["success" => 1, "active" => 1]]);

  // Current date
  $loc_date_now = new DateTime();
  $JAK_CURRENT_DATE = $loc_date_now->format('Y-m-d H:i:s');

  if (isset($sc) && !empty($sc) && is_array($sc)) foreach ($sc as $row) {
    # code...

    // We have some users let's go
    $allFailed = true;

    // First get the package
    $pack = $jakdb->get("billing_packages", ["title", "paidtill"], ["id" => $row["package"]]);

    // Check the date and how many times we have checked the payment gateway
    if ($row["paidtill"] < $JAK_CURRENT_DATE) {

      // Now we have a subscription we like to extend it
      if ($row["subscribed"] && $row["gatewaycheck"] < 4) {

        // Now let's find out if the subscription has been paid.
        $subsuccess = false;

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

            $subsuccess = $JAK_payment->JAK_pay("stripe", "", "", $row["planid"], $row["paidtill"], "recurring", "check_plan", "", "", JAK_STRIPE_SECRET_KEY, JAK_STRIPE_PUBLISH_KEY, JAK_SANDBOX_MODE);

            break;

          case 'paypal':
            // code...

            $subsuccess = $JAK_payment->JAK_pay("paypal", "", "", $row["planid"], $row["paidtill"], "recurring", "check_plan", "", "", JAK_PAYPAL_CLIENT, JAK_PAYPAL_SECRET, JAK_SANDBOX_MODE);

            break;

          case 'verifone':
            // code...

            

            break;

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

            

            break;

          case 'yoomoney':
            // code...

            // We will need to manually charge the client because YooKassa does not support automatic billing.
            $subsuccess = $JAK_payment->JAK_pay("yoomoney", $row["amount"], $row["currency"], $row["planid"], $pack["title"], "recurring", "charge", "", "", JAK_YOOKASSA_ID, JAK_YOOKASSA_SECRET, JAK_SANDBOX_MODE);


            break;

          case 'paystack':
            // code...

            $subsuccess = $JAK_payment->JAK_pay("paystack", "", "", $row["planid"], $row["paidtill"], "check_plan", "", "", "", JAK_PAYSTACK_SECRET, "", JAK_SANDBOX_MODE);

            break;
        }

        // Now let's figure out what we found out
        if ($subsuccess) {

          // Juheee we have a success the customer has been charged and everything is safe and sound

          // Get the new date
          $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
          $paidunix2 = strtotime('+2 days', $paidunix);
          $paidtill2 = date('Y-m-d H:i:s', $paidunix2);

          // We call back in 
          $paidtill = date('Y-m-d H:i:s', $paidunix);

          // Update the subscription period for the client
          $jakdb->update("clients", ["paid_until" => $paidtill2], ["AND" => ["id" => $row["clientid"], "opid" => $row['opid']]]);

          // Update the subscription table itself
          $jakdb->update("subscriptions_client", ["active" => 0, "subscribed" => 0], ["id" => $row["id"]]);

          // Payment details insert // new ones because we like to count
                $jakdb->insert("subscriptions_client", ["opid" => $row['opid'], 
                  "clientid" => $row["clientid"],
                  "amount" => $row["amount"],
                  "paidhow" => $row["paidhow"],
                  "currency" => $row["currency"],
                "package" => $row["package"],
                "subscribed" => 1,
                "planid" => $row["planid"],
                  "paidwhen" => $jakdb->raw("NOW()"),
                  "paidtill" => $paidtill,
                  "success" => 1,
                "active" => 1]);

                // We try again, do not change anything below
          $allFailed = false;


        } else {

          // We try in 12 hours again
          $jakdb->update("subscriptions_client", ["gatewaycheck[+]" => 1], ["id" => $row["id"]]);

          // We try again, do not change anything below
          $allFailed = false;

        }

      }

    }

    // Nothing worked out we cancel everything
    if ($allFailed) {

      // We have tried everything 4 times to be exact. Let's cancel the subscription and make the customer normal again.
      $jakdb->update("subscriptions_client", ["active" => 0, "subscribed" => 0], ["id" => $row["id"]]);

      // We move the user back to the standard departments
      $jakdb->update("clients", ["chat_dep" => JAK_STANDARD_CHAT_DEP, "support_dep" => JAK_STANDARD_SUPPORT_DEP, "faq_cat" => JAK_STANDARD_FAQ_CAT], ["AND" => ["id" => $row["clientid"], "opid" => $row['opid']]]);
    }

  }

  // Now if we have multi site we have fully automated process
  if (!empty(JAKDB_MAIN_NAME) && JAK_MAIN_LOC && JAK_MAIN_LOC) {
    
    // Database connection to the main site
    $jakdb1 = new JAKsql([
      // required
      'database_type' => JAKDB_MAIN_DBTYPE,
      'database_name' => JAKDB_MAIN_NAME,
      'server' => JAKDB_MAIN_HOST,
      'username' => JAKDB_MAIN_USER,
      'password' => JAKDB_MAIN_PASS,
      'charset' => 'utf8',
      'port' => JAKDB_MAIN_PORT,
      'prefix' => JAKDB_MAIN_PREFIX,
                 
      // [optional] driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
      'option' => [PDO::ATTR_CASE => PDO::CASE_NATURAL]
      ]);

    // Now we get the subscriptions
    $usrsub = $jakdb1->select("subscriptions", ["id", "packageid", "userid", "amount", "currency", "paidfor", "paidhow", "subscribed", "subscribeid", "subscribetoken", "paidwhen", "paidtill", "active", "success"], ["AND" => ["locationid" => JAK_MAIN_LOC, "active" => 1]]);

    // Current date
    $loc_date_now = new DateTime();
    $JAK_CURRENT_DATE = $loc_date_now->format('Y-m-d H:i:s');

    // Run the client subscriptions
    if (isset($usrsub) && !empty($usrsub) && is_array($usrsub)) foreach ($usrsub as $row1) {

      // We have some users let's go
      $allFailed2 = true;

      // Check the date and how many times we have checked the payment gateway
      if ($row1["paidtill"] < $JAK_CURRENT_DATE) {

        // Now we have a subscription we like to extend it
        if ($row1["subscribed"] && $row1["active"] == 1) {

          // Now let's find out if the subscription has been paid.
          $subsuccess = false;

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

              $subsuccess = $JAK_payment->JAK_pay("stripe", "", "", $row1["subscribetoken"], $row1["paidtill"], "recurring", "check_plan", "", "", JAK_STRIPE_SECRET_KEY, JAK_STRIPE_PUBLISH_KEY, JAK_SANDBOX_MODE);

              break;

            case 'paypal':
              // code...

              $subsuccess = $JAK_payment->JAK_pay("paypal", "", "", $row1["subscribetoken"], $row1["paidtill"], "recurring", "check_plan", "", "", JAK_PAYPAL_CLIENT, JAK_PAYPAL_SECRET, JAK_SANDBOX_MODE);

              break;

            case 'verifone':
              // code...

              

              break;

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

              

              break;

            case 'yoomoney':
              // code...

              // We will need to manually charge the client because YooKassa does not support automatic billing.
              $subsuccess = $JAK_payment->JAK_pay("yoomoney", $row1["amount"], $row1["currency"], $row1["subscribetoken"], $row1["paidfor"], "recurring", "charge", "", "", JAK_YOOKASSA_ID, JAK_YOOKASSA_SECRET, JAK_SANDBOX_MODE);


              break;

            case 'paystack':
              // code...

              $subsuccess = $JAK_payment->JAK_pay("paystack", "", "", $row1["subscribetoken"], $row1["paidtill"], "check_plan", "", "", "", JAK_PAYSTACK_SECRET, "", JAK_SANDBOX_MODE);

              break;
          }

          // Now let's figure out what we found out
          if ($subsuccess) {

            // Juheee we have a success the customer has been charged and everything is safe and sound

            // Get the new date
            $paidunix = strtotime($pack["paidtill"]);

            // We call back in 
            $paidtill = date('Y-m-d H:i:s', $paidunix);

            // is there any open subscription
                  $jakdb1->update("subscriptions", ["subscribeid" => 0, "subscribed" => 0, "active" => 0], ["AND" => ["locationid" => JAK_MAIN_LOC, "userid" => $custom[0], "subscribeid" => $subs["subscribeid"]]]);

                  // We insert the subscription into the main table for that user.
                  $jakdb1->insert("subscriptions", ["packageid" => $row1["packageid"],
                      "locationid" => JAK_MAIN_LOC,
                      "userid" => $row1["userid"],
                       "amount" => $row1["amount"],
                      "currency" => $row1["currency"],
                      "paidfor" => $row1["paidfor"],
                      "paidhow" => $row1["paidhow"],
                      "subscribed" => $row1["subscribed"],
                      "paygateid" => $row1["packageid"],
                      "subscribeid" => $row1["subscribeid"],
                      "subscribetoken" => $row1["subscribetoken"],
                      "paidwhen" => $jakdb->raw("NOW()"),
                      "paidtill" => $paidtill,
                      "active" => 1,
                      "success" => 1]);

                  // finally update the main database
                  $jakdb1->update("users", ["paidtill" => $paidtill], ["AND" => ["opid" => $row1["userid"], "locationid" => JAK_MAIN_LOC]]);

                  // Finally update the subscription table
                  $jakdb->update("subscriptions", ["paidwhen" => $jakdb->raw("NOW()"), "paidtill" => $paidtill], ["opid" => $row1["userid"]]);

                  // Now let us delete the define cache file
                  $cachewidget = $cron_url.JAK_CACHE_DIRECTORY.'opcache'.$row1["userid"].'.php';
                  if (file_exists($cachewidget)) {
                      unlink($cachewidget);
                  }

                  // We try again, do not change anything below
            $allFailed2 = false;


          } else {

            // We try again, do not change anything below
            $allFailed2 = false;

          }

        }


      }

      // Nothing worked out we cancel everything
      if ($allFailed2) {

        // We have tried everything 4 times to be exact. Let's cancel the subscription and make the customer normal again.
        $jakdb1->update("subscriptions", ["active" => 0, "subscribed" => 0], ["id" => $row1["id"]]);

        // We update the main table
        $jakdb->update("subscriptions", ["subscribeid" => 0, "subscribed" => 0, "planid" => "", "paidhow" => "canceled"], ["opid" => $row1["userid"]]);
      }


    }

  }

    // Write the log file each time someone tries to login before
  JAK_base::jakWhatslog('System', 0, 0, 0, 38, 0, '', 'Cron Job - Subscriptions', 'cron/subscribe.php', 0, 'subscriptions');
          
}
?>
