<?php

namespace App\Modules\Utilitarios\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use App\Modules\Utilitarios\Models\Articulo;
use App\Modules\Utilitarios\Models\Art_familia;
use App\Modules\Utilitarios\Models\Tag_art;
use App\Modules\Utilitarios\Controllers\Files_contableController;
use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
use DB;
class AutomatticController extends Controller
{
    protected $table;
    protected $art_familia;
    protected $art_tag;
    protected $woocommerce;
    function __construct(){
        $this->table = new Articulo();
        $this->woocommerce = new Client(
            env('automattic_url'),
            env('automattic_ck'), 
            env('automattic_cs'),
            ['version' => 'wc/v3',]
        );
        $this->art_familia = new Art_familia();
        $this->art_tag = new Tag_art();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
  
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
    */
    public function store(Request $request)
    {
        if ($request->has('action')) {
            $data = $request->all();
            switch ($data['action']) {
                case 'sincronizar':
                    if ($request->has('art_id')) {
                       $articulos = $this->table::where('id',$data['art_id'])->where('status_sincronization',0)->get();
                    }else{
                        $articulos = $this->table::where('status_sincronization',0)->get();
                        $this->delete_productos();
                    }
                    if ($articulos->count() > 0) {
                        foreach ($articulos as $a) {
                            if ($a->status == 1) {
                                $data = $this->sku_products($a->codigo);
                                $prod_data = array(
                                    'name'          => $a->nombre,
                                    'type'          => 'simple',
                                    'regular_price' => "$a->precio",
                                    'description'   => $a->description,
                                    'sku' => $a->codigo,
                                    'manage_stock' => true,
                                    'stock_quantity' => $a->cantidad,
                                );
                                if ($a->pvprebaja != 0) {
                                    $prod_data['sale_price'] = "$a->pvprebaja";
                                }
                                $files = new Files_contableController();
                                $imagen = $files->get_files_by_id($a->id,'Articulos'); 

                                if (!empty($imagen)) {
                                    $prod_data['images'] = array(
                                        array(
                                            'src' => url('/').'/storage/'.$imagen->nombre_archivo,
                                            'position'=>'0'
                                        )
                                    );
                                }
                            
                                $categorias = $this->art_familia->relation_has($a->id);
                                if (count($categorias) > 0) {
                                    foreach ($categorias as $c) {
                                        $prod_data['categories'] = array(
                                            array(
                                                "id" => $this->by_categories($c->slug),
                                            )
                                        );
                                    }
                                }
                                $tags = $this->art_tag->relation_has($a->id);
                                if (count($tags) > 0) {
                                    foreach ($tags as $t) {
                                        $prod_data['tags'] = array(
                                            array(
                                                "id" => $this->by_tag($t->id_tag),
                                            )
                                        );
                                    }
                                }
                                if ($data) {
                                    try{
                                        $this->woocommerce->put( 'products/'.$data->id, $prod_data );
                                        $update = $this->table::find($a->id);
                                        $update->status_sincronization = 1;
                                        $update->save();
                                    }catch (HttpClientException $e) {
                                        print_r( $e->getMessage(), true ); // Error message.
                                    }
                                }else if($data == false){
                                    try{
                                        $this->woocommerce->post('products', $prod_data);
                                        $update = $this->table::find($a->id);
                                        $update->status_sincronization = 1;
                                        $update->save();
                                    }catch (HttpClientException $e) {
                                        print_r( $e->getMessage(), true ); // Error message.

                                    }
                                }
                            }
                        }
                    }        
                break;
            }
        }else{
            return response()->json(['error'=>'No existe ningun token por favor no borre nuesto codigo html']);
        }
    }

    public function sku_products($sku){
        $data = false;
        $params = [
            'sku' => $sku
        ];
        $sku = $this->woocommerce->get('products', $params);
        if (!empty($sku)) {
            foreach ($sku as $k) {
                $data = $k;
            }
        }
        return $data;
    }
    public function delete_productos(){
        $data = $this->woocommerce->get('products');
        $articulos = $this->table::all();
        foreach ($data as $k) {
            $encontrado = false;
            foreach ($articulos as $c) {
                if ($k->sku == $c->codigo) {
                    $encontrado = true;
                }
            }
            if ($encontrado == false) {
                $this->woocommerce->delete('products/'.$k->id, ['force' => true]);
            }
        }
    }
    public function by_categories($slug){
        $params = [
            'slug' => $slug
        ];
        $data = $this->woocommerce->get('products/categories', $params);
        $retorno = 15;
        if (!empty($data)) {
            foreach ($data as $c) {
                if (strtolower($c->slug) == strtolower($slug)) {
                    $retorno = $c->id;
                }
            }
        }
        return $retorno;        
   }
   public function by_tag($slug){
        $params = [
            'slug' => $slug
        ];
        $data = $this->woocommerce->get('products/tags',$params);
        $retorno = 22;
        if (!empty($data)) {
            foreach ($data as $c) {
                if (strtolower($c->slug) == strtolower($slug)) {
                    $retorno = $c->id;
                }
            }
        }
        return $retorno;
   }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
    
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
       
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
      
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        
    }
}
