<?php

if($_POST['orders_count']){
     $orderssss = $conn->prepare('SELECT order_id FROM orders WHERE order_error=:error ORDER BY order_id  DESC');
    $orderssss->execute(array(
        'error' => '-'
    ));

     $ordersCount = $orderssss->rowCount();

echo json_encode($ordersCount);
exit;
}

$title .= $languageArray["orders.title"];

if( $_SESSION["neira_userlogin"] != 1  || $user["client_type"] == 1  ){
  Header("Location:".site_url('logout'));
}

if($_SESSION["neira_userlogin"] == 1 ):
    if($settings["sms_verify"] == 2 && $user["sms_verify"] != 2){
        header("Location:".site_url('verify/sms'));
    }
    if($settings["mail_verify"] == 2 && $user["mail_verify"] != 2 ){
        header("Location:".site_url('verify/mail')); 
    }
    endif;

  $request = route(1);
  $o_id = route(2);


  if($request == 'refill' && $o_id){
         
        if(!countRow(['table'=>'tasks','where'=>['task_type'=>2,'task_status'=>'pending','client_id'=>$user["client_id"],'order_id'=>$o_id]])){
            $orders = $conn->prepare("SELECT * FROM orders WHERE dripfeed=:dripfeed && subscriptions_type=:subs && client_id=:c_id && order_id=:id ");
            $orders-> execute(array("c_id"=>$user["client_id"],"dripfeed"=>1,"subs"=>1,"id"=>$o_id ));
            $orders = $orders->fetch(PDO::FETCH_ASSOC);
        
            $insert = $conn->prepare("INSERT INTO tasks SET client_id=:c_id, order_id=:o_id, service_id=:s_id, task_type=:type, task_date=:date ");
            $insert->execute(array("c_id"=>$orders["client_id"],"o_id"=>$orders["order_id"],"s_id"=>$orders["service_id"],"type"=>2,"date"=>date("Y-m-d H:i:s") ));
            
         
            
     
    ///////////////////////////////////
                
   $id     = $conn->lastInsertId('task_id');

if($settings["auto_refill"] != 2 ):
    $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id");
    $update = $update->execute(array("status"=>'success',"id"=>$id));
else:
    
    $smmapi   = new SMMApi(); 
    $order  = $conn->prepare("SELECT * FROM tasks LEFT JOIN services ON services.service_id = tasks.service_id LEFT JOIN orders ON orders.order_id = tasks.order_id LEFT JOIN service_api ON services.service_api = service_api.id WHERE tasks.task_id=:id ");
    $order ->execute(array("id"=>$id));
    $order  = $order->fetch(PDO::FETCH_ASSOC);
    $send_refill = $smmapi->action(array('key' =>$order["api_key"],'action' =>'refill','order'=>$order["api_orderid"]),$order["api_url"]);

    if(@$send_refill->refill):
         $update = $conn -> prepare("UPDATE orders SET refill=:refill, last_refill_time=:last_refill_time WHERE order_id=:order_id");
         $update -> execute(array("order_id"=>$order["order_id"] , "refill"=>"2","last_refill_time"=>date("Y-m-d H:i:s")));
         
        $success = 1;
        $successText = "Your refill request has been sent to your provider.";
        $r_id = $send_refill->refill;
        $update = $conn->prepare("UPDATE tasks SET task_status=:status, refill_orderid=:r_id WHERE task_id=:id");
        $update = $update->execute(array("status"=>'success',"id"=>$id,"r_id"=>$r_id));
    else:
        $send_refill = json_encode($send_refill, true);
        $error = 1;
        $errorText = "Your refill request could not be sent <code>".$send_refill."</code>";
    endif;
endif;   
            
            
            //////////////////////////////////
      
        }

else{
     $error = 1;
        $errorText = "Your refill request could not be sent";
}
            $route[1]         = "all";

  }elseif($request == 'cancel' && $o_id){
    
    try{


        if(!countRow(['table'=>'tasks','where'=>['task_type'=>1,'task_status'=>'pending','client_id'=>$user["client_id"],'order_id'=>$o_id]])){
    
            $orders = $conn->prepare("SELECT * FROM orders WHERE dripfeed=:dripfeed && subscriptions_type=:subs && client_id=:c_id && order_id=:id ");
            $orders-> execute(array("c_id"=>$user["client_id"],"dripfeed"=>1,"subs"=>1,"id"=>$o_id ));
            $orders = $orders->fetch(PDO::FETCH_ASSOC);
        
            $insert = $conn->prepare("INSERT INTO tasks SET client_id=:c_id, order_id=:o_id, service_id=:s_id, task_type=:type, task_date=:date ");
            $insert->execute(array("c_id"=>$orders["client_id"],"o_id"=>$orders["order_id"],"s_id"=>$orders["service_id"],"type"=>1,"date"=>date("Y-m-d H:i:s") ));
            
            $success    = 1;
            $successText= $languageArray["error.order.cancel"];
            
            
                           
   $id     = $conn->lastInsertId('task_id');

    
    $smmapi   = new SMMApi(); 
    $order  = $conn->prepare("SELECT * FROM tasks LEFT JOIN services ON services.service_id = tasks.service_id LEFT JOIN orders ON orders.order_id = tasks.order_id LEFT JOIN service_api ON services.service_api = service_api.id WHERE tasks.task_id=:id ");
    $order ->execute(array("id"=>$id));
    $order  = $order->fetch(PDO::FETCH_ASSOC);
    $send_cancel = $smmapi->action(array('key' =>$order["api_key"],'action' =>'cancel','order'=>$order["api_orderid"]),$order["api_url"]);

    if(@$send_cancel):
        $success = 1;
        $successText = "Your cancel request has been sent to your provider.";
        $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id");
        $update = $update->execute(array("status"=>'success','id'=> $id));
    else:
        $send_cancel = json_encode($send_cancel, true);
        $error = 1;
        $errorText = "Your cancel request could not be sent <code>".$send_cancel."</code>";
    endif;
    

        $update = $conn->prepare("UPDATE orders SET last_cancel_time=:last_cancel_time WHERE order_id=:id");
        $update->execute(array("last_cancel_time"=>date("Y-m-d H:i:s"),"id"=>$o_id));
        
        }
    }
        
        catch(\Throwable $e){
            echo $e;
            exit;
        }

        
   
            $route[1]         = "all";


  }

  $status_list = ["all", "pending", "inprogress", "completed", "partial", "processing", "canceled"];
  $search_statu = route(1);
  if (!route(1)):
      $route[1] = "all";
  endif;
  if (!in_array($search_statu, $status_list)):
      $route[1] = "all";
  endif;
  if (route(2)):
      $page = route(2);
  else:
      $page = 1;
  endif;
  if (route(1) != "all"):
      $search = "&& order_status='" . route(1) . "'";
  else:
      $search = "";
  endif;
  if (!empty($_GET["search"])):
      $search.= " && ( order_url LIKE '%" . $_GET["search"] . "%' || order_id LIKE '%" . $_GET["search"] . "%' ) ";
  endif;
  if (!empty($_GET["subscription"])):
      $search.= " && ( subscriptions_id LIKE '%" . $_GET["subscription"] . "%'  ) ";
  endif;
  if (!empty($_GET["dripfeed"])):
      $search.= " && ( dripfeed_id LIKE '%" . $_GET["dripfeed"] . "%'  ) ";
  endif;
  $c_id = $user["client_id"];
  $to = 25;
  $count = $conn->query("SELECT * FROM orders WHERE client_id='$c_id' && dripfeed='1' && subscriptions_type='1' $search ")->rowCount();
  $pageCount = ceil($count / $to);
  if ($page > $pageCount):
      $page = 1;
  endif;
  $where = ($page * $to) - $to;
  $paginationArr = ["count" => $pageCount, "current" => $page, "next" => $page + 1, "previous" => $page - 1];
  $orders = $conn->prepare("SELECT * FROM orders INNER JOIN services WHERE services.service_id = orders.service_id && orders.dripfeed=:dripfeed && orders.subscriptions_type=:subs && orders.client_id=:c_id $search ORDER BY orders.order_id DESC LIMIT $where,$to ");
  $orders->execute(array("c_id" => $user["client_id"], "dripfeed" => 1, "subs" => 1));
  $orders = $orders->fetchAll(PDO::FETCH_ASSOC);
  $ordersList = [];
  foreach ($orders as $order) {
        
        $o["refillbutton"] = false;

          $d1= new DateTime($order["last_refill_time"] ?: $order["order_create"]); // first date
          $d2= new DateTime(date("Y-m-d H:i:s")); // second date
          $day = $order["refill_days"];
          $refill_hours = $order['refill_hours'];
        $today = $order["last_refill_time"] ?: $order["order_create"] ;         
        $d3 = date ("Y-m-d H:i:s", strtotime ($today ."+ $day days"));
        $d4 = date ("Y-m-d H:i:s", strtotime ($today ."+ $refill_hours hours"));
        $d4 = new DateTime($d4);
         $interval= $d2->diff($d1); // get difference between two dates
         $interval2 = $d4->diff($d2); 
        $diff = ($interval->days * $order["refill_hours"] ) + $interval->h;
        $diff2_h = ($interval2->days * $order["refill_hours"] ) + $interval2->h;

            
            
        if( $order["order_status"] == "completed" && $order["refill_type"] == 2){
            if($d2 < new DateTime($d3)){
            if($diff >= $order["refill_hours"]){
               $o["refillbutton"] = 1; 
            }else{
                $o["refillbutton"] = false;
            }
            $o["showRefill"] = 1; 
            }
            else{
                $o["showRefill"] = 0; 
            }
            
        }
        else{
              $o["showRefill"] = 0; 
        }
            
       
        if($order["cancel_type"] == 2 && ( $order["order_status"] == 'pending' || $order["order_status"] == 'processing' || $order["order_status"] == 'inprogress' ) && !countRow(['table'=>'tasks','where'=>['task_type'=>1,'task_status'=>'pending','client_id'=>$user["client_id"],'order_id'=>$order["order_id"]]]) && !countRow(['table'=>'tasks','where'=>['task_type'=>1,'task_status'=>'canceled','client_id'=>$user["client_id"],'order_id'=>$order["order_id"]]]) && $order["last_cancel_time"] == NULL){
            
            $o["cancelButton"] = true; 
        }else{
            $o["cancelButton"] = false; 
        }

      $o["id"]    = htmlentities($order["order_id"]);
      $o["refill_available_at"] =  "سيكون متاح بعد ".$diff2_h. "ساعة " . $interval2->i." دقيقة" ;
      $o["date"]  = date("Y-m-d H:i:s", (strtotime($order["order_create"])+$user["timezone"]));
      $o["link"]    = htmlentities($order["order_url"]);
      $o["charge"]  = htmlentities($order["order_charge"]);
      $o["start_count"]  = htmlentities($order["order_start"]);
      $o["quantity"]  = htmlentities($order["order_quantity"]);
      $o["service"]  = htmlentities($order["service_name"]);
      $o["status"]  = $languageArray["orders.status.".$order["order_status"]];
      if( $order["order_status"] == "completed" && substr($order["order_remains"], 0,1) == "-" ):
        $o["remains"]  = "+".substr($order["order_remains"], 1);
      else:
        $o["remains"]  = htmlentities($order["order_remains"]);
      endif;
      array_push($ordersList,$o);
    }
