<?php

namespace App\Modules\Install\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use DB;
class InstallController extends Controller
{
    function __construct(){
        $path = base_path('install.txt');
        if (file_exists($path)) {

        }else{
            return redirect()->route('home');
        }
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('Install.views.install');
    }

    /**
     * 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')) {
            switch ($request->input('action')) {
                case 'installbd':   
                    $path = base_path('.env'); 
                    $key = array('DB_DATABASE','DB_USERNAME','DB_PASSWORD');

                    for ($i=0; $i <count($key) ; $i++) { 

                        if(is_bool(env($key[$i]))) { 

                            $old = env($key[$i])? 'true' : 'false'; 

                        } elseif(env($key[$i])===null){ 

                            $old = 'null'; 

                        } else{ 

                            $old = env($key[$i]); 
                        } 
                        if (file_exists($path)) { 
                            file_put_contents($path, str_replace( "$key[$i]=".$old, "$key[$i]=".$request->input('DB')[$i], file_get_contents($path) )); 
                        }
                    }
                    return response()->json(['success'=>'Base de datos instalada correctamente......','connect'=>'active']);
                break;
                case 'connect':
                    return $this->connect();
                break;
                case 'installtables':
                   return $this->installBD();
                break;
                case 'search_modules':
                   include_once(app_path('Modules').'/Visitas/init.php');
                break;
                 default:
                        # code...
                 break;
              }
        }
    }
    /**
     * Display connect
     *
     */
    public function connect(){
        try {
            DB::connection()->getPdo();
            if(DB::connection()->getDatabaseName()){
                return response()->json(['success'=> 'Excelente usted esta conectado a la base de datos : '.DB::connection()->getDatabaseName()]);
            }
        } catch (\Exception $e) {
            return response()->json(['error'=> 'Hubo un error por favor verifique los datos de conexion']);
        }
    }
    /**
     * Display full install tables
     *
     */
    public function installBD(){
        $path = app_path('Modules');        
        if ($handler = opendir($path)) {
            while (false !== ($file = readdir($handler))) {
                if ($file == '.' OR $file == '..') {
                    # code...
                }else{
                   $files = explode('.', $file);
                   if(is_dir(app_path('Modules').'/'.$file.'/'.'Tables')){
                        if($dir = opendir(app_path('Modules').'/'.$file.'/'.'Tables')){
                            while(($archivo = readdir($dir)) !== false){
                            if($archivo != '.' && $archivo != '..') {
                                    include_once(app_path('Modules').'/'.$file.'/'.'Tables/'.$archivo);
                                }
                            }
                            closedir($dir);
                        } 
                    }
                }
            }
            closedir($handler);
            unlink(base_path('install.txt'));
        }
        return response()->json(['success'=> 'Instalacion finalizada']);
    }

    /**
     * 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)
    {
        //
    }
}
