<?php

namespace App\Http\Controllers;

use App;
use App\Mail\PreApplicationMail;
use App\Models\ChaosEvents;
use App\Models\PreApplications;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Log;
use Nette\Utils\Random;

class PreApplicationController extends Controller
{
    public function send(Request $request){
        $event = $request->input('district_region');

        $ce = ChaosEvents::where('id', $event)->where('to_date_internal', '>=', today())->where('from_date_internal', '<=', today())->first();
        if($ce){

            $passport_type = $request->input('passport_type');
            if(!in_array($passport_type, ['d', 'k'])){
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.wrong_passport_type")];
            }

            $first_name = $request->input('first_name');
            $last_name = $request->input('last_name');
            $location = $request->input('location');

            $email = $request->input('mail');

            if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.invalid_email_format")];
            }

            switch($passport_type){
                case 'd':
                    $max_characters = 17;
                    break;
                case 'k':
                    $max_characters = 25;
                    break;
                default:
                    $max_characters = 0;
            }

            $fn = preg_match('/^[a-zA-Z0-9\s]{1,' . $max_characters . '}$/', $first_name);
            $ln = preg_match('/^[a-zA-Z0-9\s]{,' . $max_characters . '}$/', $last_name);
            $loc = preg_match('/^[a-zA-Z0-9\s]{,' . $max_characters . '}$/', $location);

            //Log::debug('fn: ' . var_export($fn, true) . ' ln: ' . var_export($ln, true) . ' loc: ' . var_export($loc, true) . '');

            if($fn && $ln && $loc){

                $free_reference_number = false;
                while(!$free_reference_number){
                    $reference_number = $ce->shortname . '-' . strtoupper($passport_type) . '-' . Random::generate(4, "0-9") . '-' . Random::generate(4, "0-9") . '-' . Random::generate(4, "0-9");
                    $free_reference_number = !PreApplications::where('reference_number', $reference_number)->exists();
                }

                try{
                    $pa = new PreApplications();
                    $pa->first_name = $first_name;
                    $pa->last_name = $last_name;
                    $pa->location = $location;
                    $pa->passport_type = $passport_type;
                    $pa->reference_number = $reference_number;
                    $pa->event_id = $event;
                    $pa->email = $email;
                    $pa->save();
                } catch(\Exception $e){
                    return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.already_submitted")];
                }

                Mail::to($email)
                    ->send(new PreApplicationMail($pa, App::getLocale()));

                return ["messageStatus" => "success", "errorMessage" => __('controller_messages.PreApplicationController.success')];
            } else {
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.invalid_characters")];
            }
        }
        return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.event_not_found")];
    }

    public static function applicationsPaginated(){
        return PreApplications::paginate(50);
    }

    public function addApplication(Request $request){
        if(Auth::check()){
            try {
                $pa = new PreApplications();
                $pa->first_name = $request->input('first_name');
                $pa->last_name = $request->input('last_name');
                $pa->location = $request->input('location');
                $pa->notes = $request->input('notes');
                $pa->passport_type = $request->input('passport_type');
                $pa->event_id = $request->input('district_region');
                $pa->email = $request->input('mail');

                $ce = ChaosEvents::find($pa->event_id);
                $free_reference_number = false;
                while(!$free_reference_number){
                    $reference_number = $ce->shortname . '-' . strtoupper($pa->passport_type) . '-' . Random::generate(4, "0-9") . '-' . Random::generate(4, "0-9") . '-' . Random::generate(4, "0-9");
                    $free_reference_number = !PreApplications::where('reference_number', $reference_number)->exists();
                }
                $pa->reference_number = $reference_number;

                $pa->save();
                return ["messageStatus" => "success", "errorMessage" => ""];
            }
            catch(\Exception $e){
                return ["messageStatus" => "failure", "errorMessage" => $e->getMessage()];
            }
        }
        abort(404);
    }

    public function deleteApplication(Request $request){
        if(Auth::check()){
            try {
                $pa = PreApplications::find($request->input('id'));
                if ($pa) {
                    $pa->delete();
                    return ["messageStatus" => "success", "errorMessage" => ""];
                } else {
                    return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.application_not_found")];
                }
            } catch(\Exception $e){
                return ["messageStatus" => "failure", "errorMessage" => $e->getMessage()];
            }
        }
        abort(404);
    }

    public function editApplication(Request $request){
        if(Auth::check()){
            try {
                $pa = PreApplications::find($request->input('id'));
                if ($pa) {
                    $pa->first_name = $request->input('first_name');
                    $pa->last_name = $request->input('last_name');
                    $pa->location = $request->input('location');
                    $pa->notes = $request->input('notes');
                    $pa->email = $request->input('mail');
                    $pa->passport_type = $request->input('passport_type');
                    $pa->save();
                    return ["messageStatus" => "success", "errorMessage" => ""];
                }
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.PreApplicationController.application_not_found")];
            } catch(\Exception $e){
                return ["messageStatus" => "failure", "errorMessage" => $e->getMessage()];
            }
        }
        abort(404);
    }
}
