<?php

namespace App\Http\Controllers;

use App\Mail\MailCustomMessage;
use App\Mail\MailVerifyAccount;
use App\Mail\MailVerifyContact;
use App\Mail\MailAccountActive;
use App\Models\UserAccount;
use App\Models\UserHistory;
use App\Repositories\ContractPDFRepository;
use App\Repositories\UserRepository;
use App\Services\SysLog;
use App\Services\UserService;
use App\User;
use Illuminate\Support\Facades\Mail;
use Request;
use Validator;

class LeadController extends Controller
{
    protected $userRepo;

    public function __construct(UserRepository $userRepo)
    {
        $this->middleware('admin');
        $this->userRepo = $userRepo;

    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $data = [
            'values' => User::where('admin', '=', 0)->where('confirmation_code_remider', '!=', 2)->get(),
        ];
        return view('admin.lead.index', $data);
    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        if($id === "new"){
            $user = new User();
            $user->account = new UserAccount();
            $user->account->same_as_billing = 1;
            $user->account->country_id = 1;
            $user->account->shipping_country_id = 1;
            $user->id = "new";
        }else{
            $user = User::findOrFail($id);
            if(!$user->account){
                $user->account = new UserAccount();
            }
        }
        $data = [
            'show' => Request::get('show'),
            'user' => $user,
            'can_change_mail' => true,
            'm_data_load' => false,
            'm_data_error' => false,
        ];
        return view('admin.lead.edit', $data);
    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editPost($id)
    {
        $m_data_load = false;
        $m_data_error = false;
        $data = Request::all();
        if(!isset($data['edit_m_data_key']) || $data['edit_m_data_key'] !== config('main.edit_data_pass')){
            $m_data_error = "Das Passwort ist falsch.";
        }else{
            $m_data_load = true;
        }

        if($id === "new"){
            $user = new User();
            $user->account = new UserAccount();
            $user->account->same_as_billing = 1;
            $user->account->country_id = 1;
            $user->account->shipping_country_id = 1;
            $user->id = "new";
        }else{
            $user = User::findOrFail($id);
            if(!$user->account){
                $user->account = new UserAccount();
            }
        }
        $next_account_id = UserAccount::max('m_account') +1;
        if($user->account->m_account === null){
            $user->account->m_account = $next_account_id;
        }

        $data = [
            'show' => 'check_lead',
            'user' => $user,
            'm_data_load' => $m_data_load,
            'm_data_error' => $m_data_error,
            'can_change_mail' => true,
            'next_account_id' => $next_account_id
        ];
        return view('admin.lead.edit', $data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function store(Request $request)
    {

        $data = Request::all();
        $show = Request::get('show');

        if ($data['user_id'] === "new" || $data['user_id'] == 0) {
            $rules = array(
                'salutation' => 'required',
                'first_name'=>'required',
                'last_name'=>'required',
                'email' => 'required|string|email|max:255|unique:users',
                'email-confirm' => 'required|same:email',
            );
        }else{
            $rules = array(
                'salutation' => 'required',
                'first_name'=>'required',
                'last_name'=>'required',
                'address'=>'required',
                'zipcode'=>'required',
                'city' => 'required',
                'email' => 'required|string|email|max:255|exists:users,email',
                'email-confirm' => 'required|same:email',
            );
            if(!Request::get('same_as_billing')){
                $rules = array_merge($rules, [
                    'shipping_firstname'=>'required',
                    'shipping_lastname'=>'required',
                    'shipping_address'=>'required',
                    'shipping_zipcode'=>'required',
                    'shipping_city' => 'required',
                    'shipping_salutation' => 'required'

                ]);
            }
        }

        if(isset($data['m_account']) && $data['m_account']){
            $user = User::findOrFail($data['user_id']);
            $rules['m_account'] = 'unique:user_accounts,m_account,'.$user->account->id.',id';


        }
        $validator = Validator::make(Request::all(), $rules);
        if ($validator->fails()) {

            if ($data['user_id'] === "new" || $data['user_id'] == 0) {
                $user_id = "new";
            }else{
                $user = User::findOrFail($data['user_id']);
                $user_id = $user->id;
            }
            return redirect(route('admin_lead_edit', [$user_id])."?show=".$show)->withErrors($validator)->withRequest(Request::all());
        }

            if ($data['user_id'] === "new" || $data['user_id'] == 0) {
                $user = new User();
                $user->id = "new";
                $user->account = new UserAccount();

            }else {
                $user = User::findOrFail($data['user_id']);
                if(!$user->account){
                    $user->account = new UserAccount();
                }
            }

            $this->userRepo->update($data);

            if(isset($data['m_data_edit']) && $data['m_data_edit'] === "TSOK"){
                $user = $this->userRepo->getModel();
                $user->m_level = isset($data['m_level']) ? $data['m_level'] : NULL;
                $user->m_sponsor = isset($data['m_sponsor']) ? $data['m_sponsor'] : NULL;
                $user->save();
            }

            if(isset($data['contact_verify'])){

                $user = $this->userRepo->getModel();

                $confirmation_code = UserService::createConfirmationCode();

                $user->lang = $user->getLandByCountry();
                $user->confirmation_code = $confirmation_code;
                //10 == start wizard form create Lead
                $user->wizard = 10;
                $user->save();
                Mail::to($user->email)->send(new MailVerifyContact($confirmation_code, $user));

                \Session()->flash('alert-save', true);
                return redirect(route('admin_leads'));
            }

            \Session()->flash('alert-save', true);
            return redirect(route('admin_lead_edit', [$user->id])."?show=".$show);




    }
    //user released when register is complete
    public function released($action, $id){

        $user = User::findOrFail($id);
        if($action === 'completed'){
            $validator = Validator::make(Request::all(), []);
            /*if(!$user->m_sponsor){
                $validator->errors()->add('m_sponsor', __('Vertriebspartner hat keinen Sponsor.'));
            }*/
            if(!$user->account->m_first_name){
                $validator->errors()->add('m_first_name', __('Vertriebspartner hat keinen Vornamen.'));
            }
            if(!$user->account->m_last_name){
                $validator->errors()->add('m_last_name', __('Vertriebspartner hat keinen Nachnamen.'));
            }

            if ($validator->errors()->count()) {
                return back()->withErrors($validator)->withRequest(Request::all());
            }

            if(!$user->account->m_account){
                $user->account->m_account = UserAccount::max('m_account') +1;
                $user->account->save();
            }

            //create PDF
            $pdf = new ContractPDFRepository($user);
            $pdf->_set('disk', 'user');
            $pdf->_set('dir', '/'.$user->id.'/documents/');
            $pdf->_set('user_id', $user->id);
            $pdf->_set('identifier', 'contract');
            $pdf->createContractPDF();

            //set wizard tp payments
            $user->wizard = 20;
            $user->active = 1;
            $user->active_date = now();
            $user->confirmation_code = null;
            $user->confirmation_code_to = null;
            $user->confirmation_code_remider = 0;
            $user->save();

            //mail with code to user?
            try {
                Mail::to($user->email)->send(new MailAccountActive($user));
            }
            catch(\Exception $e){
                SysLog::action('released', 'admin_lead', 5)
                    ->setUserId($user->id)
                    ->setModel($user->id, User::class)
                    ->setMessage('Error send released E-Mail: '.$e->getMessage())
                    ->save();
            }

            UserHistory::create(['user_id' => $user->id, 'action'=>'released_completed', 'status'=>0]);
            \Session()->flash('alert-success', "Vertriebspartner freigeschaltet!");
        }

        if($action === 'incomplete'){


            //reset release
            $confirmation_code = UserService::createConfirmationCode();
            $user->confirmation_code = $confirmation_code;
            $user->confirmation_code_to = date('Y-m-d H:i:s', strtotime('+1 week'));
            $user->confirmation_code_remider = 0;
            $user->wizard = 1;
            $user->release_account = null;
            $user->save();

            $input = Request::all();
            $data = [
                'subject' => $input['account_incomplete_subject'],
                'message' => $input['account_incomplete_message'],
                'confirmation_code' => $confirmation_code,
            ];
            try {
                Mail::to($user->email)->send(new MailCustomMessage($user, $data, \Auth::user(), true));
            }
            catch(\Exception $e){
                SysLog::action('released_incomplete', 'admin_lead', 5)
                    ->setUserId($user->id)
                    ->setModel($user->id, User::class)
                    ->setMessage('Error send released_incomplete E-Mail: '.$e->getMessage())
                    ->save();
            }
            UserHistory::create(['user_id' => $user->id, 'action'=>'released_incomplete', 'status'=>0]);
            \Session()->flash('alert-success', "E-Mail an Vertriebspartner gesendet.");

        }
        return redirect(route('admin_lead_edit', [$user->id]));
    }


    //send new verfified mail to user
    public function newMailVerified($id){

        $user = User::findOrFail($id);

        $confirmation_code = UserService::createConfirmationCode();
        $user->confirmation_code = $confirmation_code;
        $user->confirmation_code_to = date('Y-m-d H:i:s', strtotime('+1 week'));
        $user->confirmation_code_remider = 0;
        $user->save();

        try {
            Mail::to($user->email)->send(new MailVerifyAccount($confirmation_code, $user));
        }
        catch(\Exception $e){
            SysLog::action('new_mail_verified', 'admin_lead', 5)
                ->setUserId($user->id)
                ->setModel($user->id, User::class)
                ->setMessage('Error send new_mail_verified E-Mail: '.$e->getMessage())
                ->save();
        }
        UserHistory::create(['user_id' => $user->id, 'action'=>'new_mail_verified', 'status'=>0]);

        \Session()->flash('alert-success', "E-Mail erneut gesendet");
        return redirect(route('admin_lead_edit', [$user->id]));

    }

    public function deleteFile($user_id, $file_id, $relation){

        if($relation === 'upload'){
            $user = User::findOrFail($user_id);
            $file = $user->files()->findOrFail($file_id);
            //remove file
            \Storage::disk('user')->delete($file->dir.$file->filename);
            $file->delete();
            \Session()->flash('alert-success', "Datei gelöscht");
        }
        return back();
    }


    public function getLeads()
    {

        $query = User::with('account')->select('users.*')->where('users.deleted_at', '=', null)->where('users.admin', "<", 4);

        return \DataTables::eloquent($query)
            ->addColumn('first_name', function (User $user) {
                return $user->account ? $user->account->first_name : '';
            })
            ->addColumn('last_name', function (User $user) {
                return $user->account ? $user->account->last_name : '';
            })
            ->addColumn('user_level', function (User $user) {
                return $user->user_level ? $user->user_level->name : '';
            })
            ->addColumn('id', function (User $user) {
                return '<a href="' . route('admin_lead_edit', [$user->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="far fa-edit"></span></a>';
            })
            ->addColumn('confirmed', function (User $user) {
                return $user->confirmed ? '<span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
            })
            ->addColumn('active', function (User $user) {
                return $user->active ? ' <span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
            })
            ->addColumn('agreement', function (User $user) {
                return $user->agreement ? ' <span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
            })
            ->addColumn('payment_account', function (User $user) {
                return $user->payment_account ? ' <span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
            })
            ->addColumn('payment_account_date', function (User $user) {
                return $user->payment_account ? $user->getPaymentAccountDateFormat(false) : "-";
            })
            /*->addColumn('payment_shop', function (User $user) {
                return $user->payment_shop ? ' <span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
            })
            ->addColumn('payment_shop_date', function (User $user) {
                return $user->payment_shop ? $user->getPaymentShopDateFormat(false) : "-";
            })*/
            ->addColumn('turnover', function (User $user) {
                return "-";
            })
            ->addColumn('sales_total', function (User $user) {
                return "-";
            })



            ->orderColumn('id', 'id $1')
            ->orderColumn('confirmed', 'confirmed $1')
            ->orderColumn('active', 'active $1')
            ->orderColumn('agreement', 'agreement $1')
            ->orderColumn('payment_account', 'payment_account $1')
            //->orderColumn('payment_shop', 'payment_shop $1')
            ->rawColumns(['id', 'confirmed', 'active', 'agreement', 'payment_account'])
            ->make(true);
    }
}