<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class WordpressCtrl extends MY_Controller {
    public function __construct($config = 'rest')
    {
      header('Access-Control-Allow-Origin: *');
      header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Request-Method");
      header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
      header("Allow: GET, POST, OPTIONS, PUT, DELETE");
      header('content-type: application/json; charset=utf-8');
      $method = $_SERVER['REQUEST_METHOD'];
      if($method == "OPTIONS") {
          die();
      }
        parent::__construct();
    }
    public function _remap($met,$parametros = array()){
        $method = $_SERVER['REQUEST_METHOD'];
    
        if($met ==="index"){
            ($method);
            switch ($method)  
            { case 'PUT':
                $this->Edit(); 
              break;
              case 'POST': 
               $this->DesdeWorpres();
            
              break;
              case 'GET': 
                $Datso = $this->getWordpress($parametros);
                header('Content-type: application/json; charset=utf-8');
               
                echo json_encode($Datso ,JSON_PRETTY_PRINT );
               
           break;
              case 'HEAD': 
                // echo json_encode( $method ,JSON_PRETTY_PRINT );
              break; 
              case 'DELETE': 
               
              break; 
              case 'OPTIONS': 
               // echo json_encode( $method );
             break; 
             default: 
             echo json_encode( "Error" );
             break; 
            }
          }
    }
    private function Editpostmeta($ID=null,$value,$Metakey="",$post){
    if($ID!= null){
 
      EditMeta($ID,$value);
      return $ID;
    }else{
    $ID2 = addMeta($post,$Metakey,$value);
    return $ID2;
    }
   
    }
    
    private function DesdeWorpres (){
      $WOOR= $this->ConfigModels->Value("WOOR");
      if($WOOR!=TRUE){
        return;
      }
      $Datos = $this->input->raw_input_stream;
      if(is_string($Datos) ===true){
        $Datos =  json_decode($Datos, true);
      }
      if($Datos["Action"]=="POST"){
        ActualalizarExistencia($Datos["ID"]);
      }
      if($Datos["Action"]=="woocommerce"){
        Consulta_woocommerce($Datos["ID"]);
      }
      
      
    }

    private function Edit(){
      $Datos = $this->input->raw_input_stream;
      if(is_string($Datos) ===true){
        $Datos =  json_decode($Datos, true);
      }
      $Datos['_regular_price'] = $Datos['_Price'];
      //Primero verificamos si el SKU es distinto de blanco
      if($Datos['sku']!=""){
      
        Editwoocomerce($Datos['ID'],"sku",$Datos['sku']);
       $DatosPRo= $this->ReporWarehouseModels->getReporWarehouseFiltro(urldecode("sProducto^" .$Datos['sku']));
       $Datos['id_Sku']= $this->Editpostmeta($Datos['id_Sku'],$Datos['sku'],"_sku",$Datos['ID']);
       if(count($DatosPRo)>0){
        $Datos['min_price'] = $DatosPRo[0]->Precio .".0000";
        $Datos['max_price'] = $DatosPRo[0]->Precio .".0000";
        $Datos['stock_quantity'] = $DatosPRo[0]->Stock;
        $Datos['_Price'] = $DatosPRo[0]->Precio;
        $Datos['_regular_price'] = $DatosPRo[0]->Precio;
        $Datos['_Stock'] = $DatosPRo[0]->Stock;
        $Codigo ='CÃ³digo';

        $Datos['id_regular_price']= $this->Editpostmeta($Datos['id_regular_price'],$DatosPRo[0]->Precio,"_regular_price",$Datos['ID']);
        $Datos['id_Price']= $this->Editpostmeta($Datos['id_Price'],$DatosPRo[0]->Precio,"_price",$Datos['ID']);
        
        MaxMin($Datos['ID']);
        EditMeta2($Datos['ID'],'_manage_stock','yes');

        $Datos['id_Stock']= $this->Editpostmeta($Datos['id_Stock'],$DatosPRo[0]->Stock,"_stock",$Datos['ID']);


       // EditMeta($Datos['id_Stock'],$DatosPRo[0]->Stock);
       
        Editwoocomerce($Datos['ID'],"stock_quantity",$DatosPRo[0]->Stock);
        $WOOR= $this->ConfigModels->Value("WOOR");
        $MiTienda= $this->ConfigModels->Value("MiTienda");
         worpress($WOOR,$DatosPRo[0]->$Codigo,$MiTienda);
         if($DatosPRo[0]->Stock >0){
          Editwoocomerce($Datos['ID'],"stock_status",'instock');
          EditMeta2($Datos['ID'],'_stock_status','instock');
        }else{
          Editwoocomerce($Datos['ID'],"stock_status",'outofstock');
          EditMeta2($Datos['ID'],'_stock_status','outofstock');
        }
       }else{
        $Datos['id_Price']= $this->Editpostmeta($Datos['id_Price'],$Datos['_Price'],"_price",$Datos['ID']);
        $Datos['id_regular_price']= $this->Editpostmeta($Datos['id_regular_price'],$Datos['_Price'],"_regular_price",$Datos['ID']);
        MaxMin($Datos['ID']);

        if($Datos['_Stock'] != null){
          EditMeta2($Datos['ID'],'_manage_stock','yes');
         // EditMeta($Datos['id_Stock'],$Datos['_Stock']);
          $Datos['id_Stock']= $this->Editpostmeta($Datos['id_Stock'],$Datos['_Stock'],"_stock",$Datos['ID']);
          Editwoocomerce($Datos['ID'],"stock_quantity",$Datos['_Stock']);
          if($Datos['_Stock']>0){
            Editwoocomerce($Datos['ID'],"stock_status",'instock');
            EditMeta2($Datos['ID'],'_stock_status','instock');
          }else{
            Editwoocomerce($Datos['ID'],"stock_status",'outofstock');
            EditMeta2($Datos['ID'],'_stock_status','outofstock');
          }
          
        }
        
       }
      
      }else{
        Editwoocomerce($Datos['ID'],"sku",$Datos['sku']);
        $Datos['id_Sku']= $this->Editpostmeta($Datos['id_Sku'],$Datos['sku'],"_sku",$Datos['ID']);
      $Datos['id_Price']= $this->Editpostmeta($Datos['id_Price'],$Datos['_Price'],"_price",$Datos['ID']);
      $Datos['id_regular_price']= $this->Editpostmeta($Datos['id_regular_price'],$Datos['_Price'],"_regular_price",$Datos['ID']);
       MaxMin($Datos['ID']);
        if($Datos['_Stock'] != null){
          EditMeta2($Datos['ID'],'_manage_stock','yes');
          $Datos['id_Stock']= $this->Editpostmeta($Datos['id_Stock'],$Datos['_Stock'],"_stock",$Datos['ID']);
          Editwoocomerce($Datos['ID'],"stock_quantity",$Datos['_Stock']);
          Editwoocomerce($Datos['ID'],"stock_quantity",$Datos['_Stock']);
        }
        };
      
      header('Content-type: application/json; charset=utf-8');
      echo json_encode($Datos);
        
    }
    function getWordpress($parametros){
      $Cantidad = count($parametros); 
      switch ($Cantidad){
        case 0:
          return GetProduct();
        case 1:
          return GetProduct($parametros[0]);
        case 2:
          if (!is_numeric($parametros[0]) OR !is_numeric($parametros[1])) return "Error Enpoint";
          return GetProduct("",$parametros[0],$parametros[1]);
        case 3:
          if (!is_numeric($parametros[1]) OR !is_numeric($parametros[2])) return "Error Enpoint";
         
          return GetProduct(urldecode($parametros[0]),$parametros[1],$parametros[2]);
        default:
        return "Error Enpoint";
      }
      
    }
    protected function middleware()
    {
      return ["VerificacionDB"];
    }

}