<?php

namespace App\Modules\Errors\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use DB;
class ErrorController extends Controller
{
    function __construct(){

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        try { 
            DB::connection()->getPdo(); 
            if(DB::connection()->getDatabaseName()){ 
               return redirect()->route('home');
            } 
        }catch (\Exception $e) {
            return view('Errors.views.databaseerror');
        }
    }

    /**
     * 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)
    {
        $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 actualizada redireccionando......','url'=>url("home/")]);
    }

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