<?php session_start();
if(empty($_SESSION['uid'])) {
    header("location:login.php");
}


include('../../config.php');

$resp=new Response();
$debug = $GLOBALS['debugging'];
$list_of_data= [];

if(isset($_GET['type'])) {

    $_POST = json_decode(file_get_contents('php://input'), true);

    $type = $_GET['type'];

    if($type=="loadData") {

           $limit = 5;
            $page = 1;

            if($_POST["page"] > 1)
            {
                $start = (($_POST['page'] - 1) * $limit);
                $page = $_POST['page'];
            }
        
          else

            {
            $start = 0;
            }

              $query = "SELECT * FROM CustomizedShipping";

              if($_POST['query'] != '')
              {
                  $query .= ' WHERE name LIKE "%'.str_replace('', '', $_POST['query']).'%"';
              } 

                // $query .= 'ORDER BY id ASC ';

              $filter_query = $query .' LIMIT '.$start.','.$limit;
              // echo $filter_query;

                $statement = queryRunner($query);
                $total_data = countRow($statement);
                // echo "<pre>";
                // var_dump(rowRetriever($statement));
                // echo "</pre>";

                $statement = queryRunner($filter_query);
       
                // $result = rowRetriever($statement);
                $total_filter_data = countRow($statement);

                $output = '
                            <thead>
                            <tr>

                                <th>Logo</th>
                                <th>Name</th>
                                <th>Delivery Days</th>
                                <th>Country Name</th>
                                <th>Currency Code</th>
                                <th>Currency Symbol</th>
                                <th>Action</th>
                                <th>Enable</th>

                            </tr>
                          </thead>
                          <tbody>
                          
                            ';
                         
                            while ($row = rowRetriever($statement)) {
                              if($row["enable"] == 0){
                                $enable = 'value="0"';
                              }else {
                                $enable = 'checked value="1"';
                              }
                               
                                  $output .= '
                                                <tr>
                                                <td><img src="../public/image/person.jpg" alt=""></td>
                                                <td><span>Elston Gullan</span>
                                                </td>
                                                <td>2 days</td>
                                                <td>United States</td>
                                                <td>USD</td>
                                                <td>$</td>


                                                <td>
                                                <div class="">
                                                    <button type="button" data-toggle="modal" data-target="#packages_modal_form_id"
                                                    class="btn btn-outline-white2 btn-rounded btn-sm">
                                                    <i class="fas fa-plus fa-plus2"></i>
                                                    </button>
                                                    <button data-toggle="modal" data-target="#add_payment_modal_edit" id="editmodal"
                                                    type="button" class="btn btn-outline-white2 btn-rounded btn-sm">
                                                    <i class="fas fa-pencil-alt fa-pencil-alt2 mt-0"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-outline-white2 btn-rounded btn-sm">
                                                    <i class="far fa-trash-alt fa-trash-alt2 mt-0"></i>
                                                    </button>

                                                </div>
                                                </td>
                                                <td>
                                                <label class="switch">
                                                    <input type="checkbox">
                                                    <span class="slider round"></span>
                                                </label>

                                                </td>
                                                <td>
                                                <button type="button"
                                                    class="btn ml-3 accordion-toggle btn-outline-white2 text-center btn-rounded btn-sm"
                                                    id="accordion1" data-toggle="collapse" data-parent="#demo1" href="#demo1"
                                                    aria-expanded="true">
                                                    <!-- <i class="fas fa-chevron-down"></i> -->
                                                    <span class="expand-button"></span>
                                                    <!-- <img src="img/plus_icon.png" width="10px" alt=""> -->
                                                </button>
                                                </td>


                                            </tr>
                                              ';
                              }
                       

                      $output .= '   </tbody> ';

                      $total_links = ceil($total_data/$limit);
                      $previous_link = '';
                      $next_link = '';
                      $page_link = '';

                      //echo $total_links;

                      if($total_links > 4)
                      {
                          if($page < 5)
                              {
                              for($count = 1; $count <= 5; $count++)
                                  {
                                      $page_array[] = $count;
                                  }
                                  $page_array[] = '...';
                                  $page_array[] = $total_links;
                          }
                      else
                      {
                          $end_limit = $total_links - 5;
                          if($page > $end_limit)
                          {
                          $page_array[] = 1;
                          $page_array[] = '...';
                          for($count = $end_limit; $count <= $total_links; $count++)
                          {
                              $page_array[] = $count;
                          }
                          }
                          else
                          {
                              $page_array[] = 1;
                              $page_array[] = '...';
                              for($count = $page - 1; $count <= $page + 1; $count++)
                              {
                                  $page_array[] = $count;
                              }
                              $page_array[] = '...';
                              $page_array[] = $total_links;
                      }
                  }
              }
                  else
                      {
                      for($count = 1; $count <= $total_links; $count++)
                          {
                          $page_array[] = $count;
            }
              }

              for($count = 0; $count < count($page_array); $count++)
              {
                if($page == $page_array[$count])
                  {
                      $page_link .= ' <li class="page-item "><a class="page-link active" href="#">'.$page_array[$count].'</a></li> ';

                      $previous_id = $page_array[$count] - 1;
                      if($previous_id > 0)
                      {
                        $previous_link = '<li class="page-item"><a class="page-link page_pre" href="#"  data-page_number="'.$previous_id.'"><span><i class="fas fa-angle-left"></i></span></a></li>';
                      }
            
                else
                  {
                    $previous_link = '
                                        <li class="page-item disabled"><a class="page-link page_pre" href="#"><span><i
                                          class="fas fa-angle-left"></i></span></a></li>
                                      ';
                  }
                  $next_id = $page_array[$count] + 1;
                  if($next_id > $total_links)
                  {
                      $next_link = '
                          <li class="page-item disabled"><a class="page-link page_next" href="#" data-page_number="'.$next_id.'"><span><i
                          class="fas fa-angle-right"></i></span></a></li>
                          ';
                  }
                  else
                  {
                      $next_link = '<li class="page-item"><a class="page-link page_next" href="#" data-page_number="'.$next_id.'"><span><i class="fas fa-angle-right"></i></span></a></li>';
                  }
                  }
                  else
                    {
                      if($page_array[$count] == '...')
                        {
                          $page_link .= '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                        }
                      else
                      {
                          $page_link .= '<li class="page-item"><a class="page-link" href="#" data-page_number="'.$page_array[$count].'">'.$page_array[$count].'</a></li>
                
                                      ';
                      }
                    }
                }
                $output2 = '<ul class="pagination pagination-sm">';
                $output2 .= $previous_link . $page_link . $next_link;
                $output2 .= '</ul>';
                if($total_data > 0){
                    $resp -> code = $success_code;
                    $resp -> message = "get data  ";
                    $resp -> response = $output;
                    $resp -> pagenate = $output2;
                }
                else{
                  
                    $resp -> code = $error_code;
                    $resp -> message = "Error Insert Data ";
                  }
              echo json_encode($resp);


    }

    else if($type=="delete_Banner"){
        
      $id = $_POST['id'];
      
      $query="DELETE FROM FeaturedBanner WHERE id = '$id'";
      $result = queryRunner($query);
      if($result!=null){
          echo $success_code;
      }
      else{
          echo $error_code;
      }
      
      
    }

    else if($type=="update_banner"){
        
      ///var_dump($_POST);
      
      $id = $_POST['id'];
      // $category_name = $_POST['category_name'];
      $banner_status = $_POST['enable'];

      
      
      ////echo "Id = ".$id." Name = ".$category_name." Picture = ".$category_picture;
      
      $query="UPDATE FeaturedBanner SET enable = '$banner_status'  WHERE id='$id' ";
     
      
      $result = queryRunner($query);
      if($result!=null) {
          echo $success_code;
      }
      else{
          echo $error_code;
      }
      
      
    }

    else if($type=="list_of_brands") {
      
      $list_of_data = [];

      $query="SELECT * FROM Brand";
      $result = queryRunner($query);
      while ($row = rowRetriever($result)) {
      //  $pic_path = image_resize(, 40, 40);
      //  echo $pic_path;
             array_push($list_of_data, [
                  'id' => $row['id'] , 
                  'name' => $row['name'], 
                  // 'image'=> $category_images.$row['image'],
                  // 'enable' => $row['enable']
              ]);
      }
      if(count($list_of_data)>0){
          echo json_encode($list_of_data);
      }
      else{
          echo $error_code;
      }

    }

    else if($type=="list_of_products"){

      $list_of_data = [];
      $brand_id = $_POST['brand_id'];
      
      $query="SELECT * FROM Product WHERE brand_id='$brand_id' ";
      $result = queryRunner($query);
      while ($row = rowRetriever($result)) {
      //  $pic_path = image_resize(, 40, 40);
      //  echo $pic_path;
             array_push($list_of_data, [
                  'id' => $row['id'] , 
                  'name' => $row['name'], 
                  // 'image'=> $category_images.$row['image'],
                  // 'enable' => $row['enable']
              ]);
      }
      if(count($list_of_data)>0){
          echo json_encode($list_of_data);
      }
      else{
          echo $error_code;
      }
      
      
    }

    else if($type=="add_featured_banner"){
        
      ///var_dump($_POST);
      
      $banner_name = $_POST['banner_name'];     
      $brand_id = $_POST['brand_id'];
      $image = $_POST['image'];
      $select_brand = $_POST['select_brand'];
      $product_id = $_POST['product_id'];
     
      
      

      $banner_image=convert_save_image_from_base64("ic_category_picture".rand().".webp",$image,$featured_banner_images);
     
      $query="INSERT INTO FeaturedBanner (name,image,type) VALUES('$banner_name','$banner_image','$select_brand')";
      
      $result = queryRunner($query);
      $feature_id=findLastInsertId();
      if(is_array($product_id)){
        // $product_id= implode(', ', $product_id);
        foreach ($product_id as $value) {

          $query="INSERT INTO FeaturedBannerMeta (featured_id,store_id,product_id) VALUES('$feature_id','$brand_id','$value')";

          $result = queryRunner($query);
        }
      } else {
        $query="INSERT INTO FeaturedBannerMeta (featured_id,store_id,product_id) VALUES('$feature_id','$brand_id','$product_id')";

        $result = queryRunner($query);
      }
     
     
      // echo  $result;
      if($result!=null) {
          echo $success_code;
      }
      else{
          echo $error_code;
      }
      
      
    }

    else if($type=="getData_Update"){
     
      $id = $_POST['id'];

      $query="SELECT feat_banner.*,feat_meta.*,feat_meta.id as metaid 
      FROM FeaturedBanner feat_banner 
      INNER JOIN FeaturedBannerMeta as feat_meta ON  feat_banner.id = feat_meta.featured_id 
      WHERE feat_banner.id ='$id' ";
      // echo $query;
      $result = queryRunner($query);
      while ($row = rowRetriever($result)) {
     
          $brand_id=$row['store_id'];

             array_push($list_of_data, [
                  'id' => $row['id'] , 
                  'name' => $row['name'], 
                  'image'=> $featured_banner_images.$row['image'],
                  'type' => $row['type'],
                  'store' => $row['store_id'],
                  'product_id' => $row['product_id'],
              ]);
      }
      
      $list_of_product=[];
      $query="SELECT * FROM Product WHERE brand_id='$brand_id'";
      $result = queryRunner($query);
      while ($row = rowRetriever($result)) {
        $selected=false;
        for($i=0; $i < count($list_of_data); $i++){

         
          if($list_of_data[$i]['product_id'] == $row['id'] ){

            $selected=true;

          }
        }
       
            array_push($list_of_product, [
                    'id' => $row['id'] , 
                    'name' => $row['name'], 
                    'selected' => $selected,
                ]);
               
        }
      //  var_dump($list_of_product); 
      if(count($list_of_data)>0){
        $resp -> code = $success_code;
        $resp -> message = "get data  ";
        $resp -> response=$list_of_data;
        $resp -> product=$list_of_product;
      }
        else{
            $resp -> code = $error_code;
            $resp -> message = "Error Insert Data ";
        }
        echo json_encode($resp);


    }

    else if($type=="update_featured"){
        
    
      $id = $_POST['id'];   
      $banner_name = $_POST['banner_name'];     
      $brand_id = $_POST['brand_id'];
      $image = $_POST['image'];
      $select_brand = $_POST['select_brand'];
      $product_id = $_POST['product_id'];
     
      $query="DELETE FROM FeaturedBannerMeta WHERE featured_id = '$id'";
     
      $result = queryRunner($query);
      
      $query="UPDATE FeaturedBanner SET name = '$banner_name' , type = '$select_brand' %s  WHERE id='$id' ";
   
      
      if (!isPath($image)) {
          
        $banner_image=convert_save_image_from_base64("ic_category_picture".rand().".webp",$image,$featured_banner_images);
          $query = sprintf($query," , image ='$banner_image' ");
          
      }
      else{
          
          $query = sprintf($query," ");
          
      }
   
      $result = queryRunner($query);
    
      if(is_array($product_id)){
      
        foreach ($product_id as $value) {

          $query="INSERT INTO FeaturedBannerMeta (featured_id,store_id,product_id) VALUES('$id','$brand_id','$value')";

          $result = queryRunner($query);
        }
      } else {
        $query="INSERT INTO FeaturedBannerMeta (featured_id,store_id,product_id) VALUES('$id','$brand_id','$product_id')";

        $result = queryRunner($query);
      }
     
  
      if($result!=null) {
          echo $success_code;
      }
      else{
          echo $error_code;
      }
      
      
    }


}

else {

}
 function getshippingpackages($id){
    $query = "SELECT * FROM CustomizedShipping";
    $result = queryRunner($query);

    while ($row = rowRetriever($statement)) {


    }

 }