<?php

namespace App\Modules\Install\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Storage;
use App\Modules\Install\Models\Modules_install;
use App\Http\Controllers\Controller;
use DB;
use Session;
use ZipArchive;
class ModuleInstallController extends Controller
{
    protected $table;
    function __construct(){
        $this->table = new Modules_install();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->get_modules();
        $installed = Modules_install::all();
        return view('Install.views.modules')->with('data',['get'=>$data,'installed'=>$installed]);

    }

    /**
     * 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 'install':
                    
                    return $this->move_files($data['carpeta']);
                    
                break;
                case 'submitfile':
                    $allowedfileExtension=['zip'];
                    $file = $request->file('file');
                    $check=in_array($file->getClientOriginalExtension(),$allowedfileExtension);
                    if ($check) {

                        $path = $file->store('/',['disk' => 'modules_public']);
                        if (file_exists(app_path('Modules').'/'.$path)) {
                    		return response()->json(['error'=>array('Existe un modulo con el mismo nombre , por favor verifique o cambie  la informacion del moudlo')]);
                    	}else{
	                        $zip = new ZipArchive;
	                        if (!empty($path)) {
	                            if ($zip->open(app_path('Modules').'/'.$path) === TRUE) {
	                                $zip->extractTo(app_path('Modules'));
	                                $zip->close();
	                                unlink(app_path('Modules').'/'.$path);
	                                Session::flash('install_success','Modulo subido con exito');
	                                return response()->json(['Success'=>'Modulo subido con exito', 'url'=> url('moduleinstall')]);
	                            }else{
	                               return response()->json(['error'=>array('No se pudo descomprimir el zip')]);
	                            }
	                        }
                        }
                    }else{
                        return response()->json(['error'=>array('Solo se permiten archivos zip')]);
                    }
                break;
                default:
                    # code...
                break;
            }
        }
    }

    public function get_modules(){
        $path = app_path('Modules');        
        $data = array();
        if ($handler = opendir($path)) {
            while (false !== ($file = readdir($handler))) {
                if ($file == '.' OR $file == '..') {
                   
                }else{
                   if(file_exists(app_path('Modules').'/'.$file.'/'.'install_module.xml')){
                        $file = simplexml_load_file(app_path('Modules').'/'.$file.'/'.'install_module.xml');
                        foreach ($file as $m) {
                            $data[] = $m;
                        }            
                         
                    }
                }
            }
            closedir($handler);
        }
        return $data;
    }
    /**
     * Display full install tables
     *
     */
    public function installBD($module){
        $path = app_path('Modules/'.$module);        
        if ($handler = opendir($path)) {
            while (false !== ($file = readdir($handler))) {
                if ($file == '.' OR $file == '..') {
                    # code...
                }else{
                   if(is_dir($path.'/Tables')){
                        if($dir = opendir($path.'/Tables')){
                            while(($archivo = readdir($dir)) !== false){
                                if($archivo != '.' && $archivo != '..') {
                                    include_once($path.'/Tables/'.$archivo);
                                }
                            }
                            closedir($dir);
                        } 
                    }
                }
            }
            closedir($handler);
        }
        return true;
    }
    public function move_files($carpeta){
       $path = app_path('Modules/'.$carpeta);
       $errors = array();   
       if(file_exists($path.'/install_module.xml')){        
            if (is_dir($path.'/view_functions')) {
              if ($handler = opendir($path.'/view_functions')) {
                while (false !== ($file = readdir($handler))) {
                    if ($file != '.' AND $file != '..') {
                        $destino = base_path('public/assets/views_functions');
                        if (file_exists($destino.'/'.$file)) {
                        	$errors[] =  'La funcion '.$file.' Ya existe en nuestros archivos , verifique  y copie manualmente esa funcion';
                        }else{
	                        if (!copy($path.'/view_functions/'.$file, $destino.'/'.$file)) {
	                            $errors[] =  'Hubo un error al copiar la funcion'.$file;
	                        }
                        }
                    }
                }
              }
            }
            if (count($errors) > 0) {
            	return response()->json(['error'=>$errors]);
            }
            $file = simplexml_load_file($path.'/install_module.xml');
            foreach ($file as $m) {
                //Add route web.php
                $f = fopen(base_path('routes/web.php'),"a");
                fwrite($f, $m->ruta.PHP_EOL);
                fclose($f);
                $this->table->module = $m->nombre;
                $this->table->version = $m->version;
                $this->table->carpeta = $m->carpeta;
                $this->table->ruta = $m->ruta;
                $this->table->created_at = now();
                $this->table->save();
            } 
            if (!$this->installBD($carpeta)) {
	        	return response()->json(['error'=>array('Hubo un error al subir las tablas y datos de su modulo')]);
	        }   
            unlink($path.'/install_module.xml');
        } 
        Session::flash('install_success','Modulo instalado con exito');
        return response()->json(['success'=>'Registro actualizado con exito','url' => url('moduleinstall')]);
    }
    /**
     * 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)
    {
        //
    }
}
