<?php

namespace RtRasel\LaravelInstaller\Controllers;

use Exception;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use RtRasel\LaravelInstaller\Constants\Installer;
use RtRasel\LaravelInstaller\Helpers\EnvironmentManager;

class EnvironmentController extends Controller
{
    /**
     * @var EnvironmentManager
     */
    protected $EnvironmentManager;

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

    /**
     * Display the Environment menu page.
     *
     * @return \Illuminate\View\View
     */
    public function environment()
    {
        if(!session('license')){
            return redirect()->back();
        }

        return view('laravelinstaller::environment');
    }

    /**
     * Processes the newly saved environment configuration.
     *
     * @param  Request  $request
     * @param  Redirector  $redirect
     */
    public function save(Request $request)
    {        
        $rules = Installer::CONFIG['environment']['form']['rules'];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return redirect()->route('LaravelInstaller::environment')->withInput()->withErrors($validator->errors());
        }

        if (! $this->checkDatabaseConnection($request)) {
            return redirect()->route('LaravelInstaller::environment')->withInput()->withErrors([
                'database_connection_failed' => __('Could not connect to the database.'),
            ]);
        }

        $response = $this->EnvironmentManager->saveFile($request);
        if ($response['status'] === 'error') {
            return redirect()->route('LaravelInstaller::environment')->withInput()->withErrors([
                'env_save_failed' => __($response['message']),
            ]);
        }

        return redirect()->route('LaravelInstaller::database');
    }

    /**
     * Validate database connection with user credentials.
     *
     * @param  Request  $request
     * @return bool
     */
    private function checkDatabaseConnection(Request $request)
    {
        $connection = 'mysql';

        $settings = config("database.connections.$connection");

        config([
            'database' => [
                'default' => $connection,
                'connections' => [
                    $connection => array_merge($settings, [
                        'driver' => $connection,
                        'host' => $request->input('database_hostname'),
                        'port' => $request->input('database_port'),
                        'database' => $request->input('database_name'),
                        'username' => $request->input('database_username'),
                        'password' => $request->input('database_password'),
                    ]),
                ],
            ],
        ]);

        DB::purge();

        try {
            DB::connection()->getPdo();

            return true;
        } catch (Exception $e) {
            return false;
        }
    }
}
