<?php

namespace RtRasel\LaravelInstaller\Controllers;
use Exception;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use RtRasel\LaravelInstaller\Constants\Installer;
use RtRasel\LaravelInstaller\Helpers\LicenseManager;

class VerifyController extends Controller
{
    /**
     * @var LicenseManager
     */
    protected $LicenseManager;

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

    /**
     * Display the verify license page.
     *
     * @return \Illuminate\Http\Response
     */
    public function welcome()
    {        
        return view('laravelinstaller::verify.welcome');
    }

    /**
     * Verify License
     *
     * @param  Request  $request
     * @param  Redirector  $redirect
     */
    public function verify(Request $request)
    {
        $rules = Installer::CONFIG['license']['form']['rules'];

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

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

        $result = $this->verifyLicense($request);
        if (!$result) {
            return redirect()->route('LaravelVerifier::welcome')->withInput()->withErrors([
                'license_verification' => __('License Verification Failed'),
            ]);
        }

        if (!$result['status']) {
            return redirect()->route('LaravelVerifier::welcome')->withInput()->withErrors([
                'license_verification' => __($result['message']),
            ]);
        }

        return redirect()->route('home');
    }

    private function verifyLicense(Request $request){
        return $this->LicenseManager->activate_license($request->license_code);
    }

}
