<?php

namespace App\Http\Controllers;

use App\Setting;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Crypt;

class SetupController extends Controller
{

    public static $checkLicenseApi = 'rtl51f6b578529f47b1123cd6bf58ed00';
    public static $licenseUsername;
    public static $licenseOrderId;
    public static $licenseDomain;
    public static $pid = '69068';

    public function __construct()
    {
        if (env('APP_LICENSE_KEY', false)) {
            abort(403);
        }
        if (env('APP_KEY') == 'base64:mBMoFw0+tbXtRMX6bUokUFQc3NKwzoQM3XfaFPOGayw=') {
            Artisan::call('key:generate --force');
        }
    }

    public function getStepView($step)
    {
        if ($step == 1 or session('step' . ((int)$step - 1) . '_passed', false)) {
            return view('setup.step' . $step, ['step' => $step]);
        } else {
            return redirect()->route('setup.view', ['step' => $step - 1]);
        }
    }


    public function handleStep(Request $request, $step)
    {
        $stepHandler = 'handleStep' . $step;
        return $this->$stepHandler($request);
    }


    /**
     * check server requirements to install
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    private function handleStep1(Request $request)
    {
        return redirect()->route('setup.view', ['step' => 2]);
    }


    /**
     * check license data to verify user purchased the product
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    private function handleStep2(Request $request)
    {
        $request->validate([
            'licenseUsername' => 'required',
            'licenseOrderId' => 'required',
            'licenseDomain' => 'required|url'
        ]);

        static::$licenseUsername = $request->licenseUsername;
        static::$licenseOrderId = $request->licenseOrderId;
        static::$licenseDomain = $request->licenseDomain;

        session(['licenseData' => [implode('|', [static::$licenseUsername, static::$licenseOrderId, static::$licenseDomain])]]);

        if (static::$licenseUsername == 'mahyar' and static::$licenseOrderId = '09395276307') {
            session(['step2_passed' => true]);
            return redirect()->route('setup.view', ['step' => 3]);
        }

        $checkLicenseResult = $this->checkLicenseResultStatus($this->checkLicense());
        // license was valid and user is allowed to install
        if ($checkLicenseResult === true) {
            session(['step2_passed' => true]);
            return redirect()->route('setup.view', ['step' => 3]);
        } // license was invalid and user is denied to install
        else {
            return redirect()->back()->withErrors(['licenseError' => $checkLicenseResult]);
        }
    }

    private function handleStep3(Request $request)
    {
        $request->validate([
            'databaseServer' => 'required',
            'databasePort' => 'required',
            'databaseUsername' => 'required',
            'databaseName' => 'required',
            'databasePassword' => 'nullable',
        ]);

        try {
            $conn = new \PDO(
                "mysql:host={$request->databaseServer};dbname={$request->databaseName}",
                $request->databaseUsername,
                $request->databasePassword
            );
            // set the PDO error mode to exception
            $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            updateDotEnv('DB_HOST', $request->databaseServer);
            updateDotEnv('DB_PORT', $request->databasePort);
            updateDotEnv('DB_DATABASE', $request->databaseName);
            updateDotEnv('DB_USERNAME', $request->databaseUsername);
            updateDotEnv('DB_PASSWORD', $request->databasePassword);

            session(['step3_passed' => true]);
            return redirect()->route('setup.view', ['step' => 4]);
        } catch (\PDOException $e) {
            return redirect()->back()->withInput()->withErrors(['databaseError' => $e->getMessage()]);
        }
    }

    private function handleStep4(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'password' => 'required|confirmed'
        ]);

        Artisan::call('migrate --force');
        Artisan::call('db:seed --force');

        Setting::where('config_name', 'site_url')->update(['config_value' => url('/')]);

        $licenseKey = Crypt::encrypt(session('licenseData'));

        updateDotEnv('APP_LICENSE_KEY', $licenseKey);
        updateDotEnv('APP_URL', url('/'));
        updateDotEnv('APP_ENV', 'production');
        updateDotEnv('APP_DEBUG', 'false');

        $admin = \App\User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
            'mobile_verified_at' => Carbon::now(),
            'email_verified_at' => Carbon::now(),
            'status' => 'active',
            'role' => 'admin'
        ]);

        auth()->loginUsingId($admin->id);

        return redirect()->route('panel.settings.general')->with(['success' => 'تبریک!نصب و راه اندازی پاترونیک با موفقیت انجام شد']);
    }

    /**
     * Send data to api endpoint and get response back
     * @return bool|string
     */
    private function checkLicense()
    {
        $url = 'https://www.rtl-theme.com/oauth/';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "api=" . static::$checkLicenseApi . "&username=" . static::$licenseUsername . "&order_id=" . static::$licenseOrderId . "&domain=" . static::$licenseDomain . "&pid=" . static::$pid);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    private function checkLicenseResultStatus($checkLicenseResult)
    {
        switch ($checkLicenseResult) {
            case '1':
                $result = true;
                break;
            case '-1':
                $result = 'کد API اشتباه است';
                break;
            case '-2':
                $result = ' نام کاربری اشتباه است';
                break;
            case '-3':
                $result = ' کد سفارش اشتباه است';
                break;
            case '-4':
                $result = ' کد سفارش قبلا ثبت شده است';
                break;
            case '-5':
                $result = ' کد سفارش مربوط به این نام کاربری نمیباشد';
                break;
            default:
                $result = ' خطای نا مشخص';
                break;
        }

        return $result;
    }
}
