<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}

  $smmapi = new SMMApi();
  $fapi   = new socialsmedia_api();

  if( route(2) && is_numeric(route(2)) ):
      $page = route(2);
    else:
      $page = 1;
    endif;

  // 🔥 CUSTOM SQL FIELDS TO MATCH YOUR VIEW Perfectly!
  $select_fields = "tasks.task_id as id, tasks.refill_orderid as refill_apiid, clients.username, tasks.order_id, orders.api_orderid as order_apiid, orders.order_url, services.service_name, tasks.task_created_at as creation_date, tasks.task_status as refill_status, IF(tasks.task_api = 0, 'manual', 'api') as refill_where";
  
  $joins = "INNER JOIN clients ON clients.client_id = tasks.client_id 
            INNER JOIN orders ON orders.order_id = tasks.order_id 
            INNER JOIN services ON services.service_id = tasks.service_id";
            
  $base_where = "tasks.task_type = 1"; // 1 means Refill Task


 if( $_GET["search_type"] == "refill_apiid" && $_GET["search"] ):
      $search_where = $_GET["search_type"];
      $search_word  = urldecode($_GET["search"]);
      
      $count        = $conn->prepare("SELECT * FROM tasks WHERE task_type = 1 AND refill_orderid LIKE :search");
      $count        -> execute(array("search"=>"%".$search_word."%"));
      $count        = $count->rowCount();
      $search_link  = "?search=".$search_word."&search_type=".$search_where;
        
    $to             = 25;
    $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];
    
    $refills         = $conn->prepare("SELECT $select_fields FROM tasks $joins WHERE $base_where AND tasks.refill_orderid LIKE :search LIMIT $where, $to ");
    $refills -> execute(array("search"=>"%".$search_word."%"));
    $refills  = $refills->fetchAll(PDO::FETCH_ASSOC);
    
    elseif( $_GET["search_type"] == "order_id" && $_GET["search"] ):
      $search_where = $_GET["search_type"];
      $search_word  = urldecode($_GET["search"]);
      
      $count        = $conn->prepare("SELECT * FROM tasks WHERE task_type = 1 AND order_id LIKE :search");
      $count        -> execute(array("search"=>"%".$search_word."%"));
      $count        = $count->rowCount();
      $search_link  = "?search=".$search_word."&search_type=".$search_where;
        
    $to             = 25;
    $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];
    
    $refills         = $conn->prepare("SELECT $select_fields FROM tasks $joins WHERE $base_where AND tasks.order_id LIKE :search LIMIT $where, $to ");
    $refills -> execute(array("search"=>"%".$search_word."%"));
    $refills  = $refills->fetchAll(PDO::FETCH_ASSOC);
      
    else :
    $count        = $conn->prepare("SELECT * FROM tasks WHERE task_type = 1");
    $count        -> execute(array());
    $count        = $count->rowCount();
    $to             = 25;
    $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];
    
    $refills = $conn->prepare("SELECT $select_fields FROM tasks $joins WHERE $base_where ORDER BY tasks.task_id DESC LIMIT $where, $to");
    $refills->execute(array());
    $refills = $refills->fetchAll(PDO::FETCH_ASSOC);

  endif;
  
  
if( route(2) == "multi-action" ):
          $orders   = $_POST["order"];
          $action   = $_POST["bulkStatus"];
          
          $status_map = [
              "Pending" => "pending",
              "Refilling" => "inprogress",
              "Completed" => "completed",
              "Rejected" => "rejected",
              "Error" => "error"
          ];
          
          if(array_key_exists($action, $status_map)) {
              $db_status = $status_map[$action];
              foreach ($orders as $id => $value):
                $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id ");
                $update->execute(array("status"=>$db_status,"id"=>$id));
              endforeach;
          }
          header("Location:".site_url("admin/refill"));
      exit();
endif;

// Single Action Handlers (Approve/Reject from Table Actions)
if( route(2) == "refill_Pending" ):
    $id     = route(3);
    $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id ");
    $update->execute(array("status"=>"pending","id"=>$id));
    header("Location:".site_url("admin/refill"));
elseif( route(2) == "refill_Error" ):
    $id     = route(3);
    $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id ");
    $update->execute(array("status"=>"failed","id"=>$id));
    header("Location:".site_url("admin/refill"));
elseif( route(2) == "refill_refilling" ):
    $id     = route(3);
    $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id ");
    $update->execute(array("status"=>"inprogress","id"=>$id));
    header("Location:".site_url("admin/refill"));
elseif( route(2) == "refill_complete" ):
    $id     = route(3);
    $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id ");
    $update->execute(array("status"=>"completed","id"=>$id));
    header("Location:".site_url("admin/refill"));
elseif( route(2) == "refill_reject" ):
    $id     = route(3);
    $update = $conn->prepare("UPDATE tasks SET task_status=:status WHERE task_id=:id ");
    $update->execute(array("status"=>"rejected","id"=>$id));
    header("Location:".site_url("admin/refill"));
endif;
  
 require admin_view('refill');
?>