<?php

namespace RachidLaasri\LaravelInstaller\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Artisan;
use RachidLaasri\LaravelInstaller\Helpers\EnvironmentManager;
use Illuminate\Support\Facades\Validator;

class EnvironmentController extends Controller
{

    /**
     * @var EnvironmentManager
     */
    protected $EnvironmentManager;

    /**
     * @param EnvironmentManager $environmentManager
     */
    public function __construct(EnvironmentManager $environmentManager)
    {
        $this->EnvironmentManager = $environmentManager;
    }

    /**
     * Display the Environment page.
     *
     * @return \Illuminate\View\View
     */
    public function environment()
    {
        $this->EnvironmentManager->getEnvContent();
        return view('vendor.installer.environment');
    }


    /**
     * Processes the newly saved environment configuration and redirects back.
     *
     * @param Request $input
     * @param Redirector $redirect
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $input, Redirector $redirect)
    {
        $message = $this->EnvironmentManager->saveFile($input);


        return $redirect->route('LaravelInstaller::environment')
                        ->with(['message' => $message]);
    }


    /**
     *
     * Saving the env file 
     *
     */
    public function saveEnv(Request $request)
    {

        $this->validateRequest( $request );

        Artisan::call('key:generate');


        // Env 
        $env_update = $this->changeEnv([
            'DB_HOST'       => $request->db_host,
            'DB_DATABASE'   => $request->db_database,
            'DB_USERNAME'   => $request->db_username,
            'DB_PASSWORD'   => $request->db_password,
            'DB_PREFIX'     => $request->db_prefix
        ]);

        if($env_update){
            return redirect()->route('LaravelInstaller::requirements');
        } else {
            return redirect()->back();
        }
    }


    /**
     *
     * Update the env file
     *
     */
    
    public function changeEnv($data = array())
    {
        if(count($data) > 0){

            // Read .env-file
            $env = $this->EnvironmentManager->getEnvContent();

            // Split string on every " " and write into array
            $env = preg_split('/\s+/', $env);;

            // Loop through given data
            foreach((array)$data as $key => $value){

                // Loop through .env-data
                foreach($env as $env_key => $env_value){

                    // Turn the value into an array and stop after the first split
                    // So it's not possible to split e.g. the App-Key by accident
                    $entry = explode("=", $env_value, 2);

                    // Check, if new key fits the actual .env-key
                    if($entry[0] == $key){
                        // If yes, overwrite it with the new one
                        $env[$env_key] = $key . "=" . $value;
                    } else {
                        // If not, keep the old one
                        $env[$env_key] = $env_value;
                    }
                }
            }

            // Turn the array back to an String
            $env = implode("\n", $env);

            // And overwrite the .env with the new data
            file_put_contents(base_path() . '/.env', $env);
            
            return true;
        } else {
            return false;
        }
    }


    /**
     *
     * Validate the request
     *
     */
    public function validateRequest( $request )
    {
        $this->validate($request, [
            'db_host' => 'required',
            'db_database' => 'required',
            'db_username' => 'required',
        ]);   
    }

}
