<?php

/*
 * *************************************************
 * Copyright (C) 2020 Earworks.                    *
 * Codeigniter Project Template Modification       *
 * Please contact our email for more information : *
 * contact@earworks.co.id                          *
 * *************************************************
 */

defined('BASEPATH') OR exit('No direct script access allowed');

use Illuminate\Database\Capsule\Manager as Capsule;

/**
 * Description of Login
 *
 * @author andhy
 */
class Login extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        Ci::set_layout_file('main_login');
        Ci::helper('form');
    }

    public function index($location = 'jakarta') {
        redirect('/'); // gk ada login
        $data = [
            'phone' => $this->post('phone'),
            'password' => $this->post('password'),
            'rememberme' => $this->post('rememberme')
        ];

        $validate = $this->validate_form(['phone'], false);

        if ($validate === true) {
            $phone = $data['phone'] ? phone($data['phone']) : null;
            $model = User_model::get_dbo()->where('username', $phone)->first();
            if ($phone && $model) {
                $this->_auto_login($model);
                redirect('dashboard/profile');
            } else {
                $this->session->set_flashdata('error', 'No Telepon tidak tersedia.');
            }

//            $data['username'] = phone($data['phone']);
//            $result = $model->login($data, User_model::LOGIN_TYPE_VISITOR);
//            if ($result['status'] === 1) {
//                redirect('dashboard/profile');
//            } else {
//                $this->session->set_flashdata('error', $result['message']);
//            }
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }

        Ci::view(__METHOD__, [
            'data' => $data,
            'redir' => $this->get_redir(true)
        ]);
    }

    public function register($location = 'general', $id = null) {
        $model = new User_model();
        $profile_model = new User_profile_model();
        // Post Data
        if (!$id) {
            $data_user = [
                'phone' => $this->post('phone'),
                'password_default' => $this->post('password_default'),
                'status' => $this->post('status', User_model::STATUS_ACTIVE),
            ];
            $data_profile = [
                'name' => $this->post('name'),
                'location' => $this->post('location'),
                'card_name' => $this->post('card_name'),
                'info_tambahan' => $this->post('info_tambahan'),
                'email' => $this->post('email'),
                'optic' => $this->post('optic'),
                'province' => $this->post('province'),
                'city' => $this->post('city'),
                'district' => $this->post('district'),
                'sub_district' => $this->post('sub_district'),
                'poscode' => $this->post('poscode'),
                'address' => $this->post('address'),
                'pax' => $this->post('pax'),
                'pax_name' => $this->post('pax_name'),
                'pax_email' => $this->post('pax_email'),
                'pax_phone' => $this->post('pax_phone'),
                'table' => $this->post('table'),
                'seat' => $this->post('seat'),
                'privacy' => $this->post('privacy'),
                'inform' => $this->post('inform'),
                'main_course' => $this->post('main_course'),
                'alergy' => $this->post('alergy')
            ];
        } else {
            $saved = User_data_model::get_dbo()->where('id', $id)->first();
            if (!$saved) {
                $this->session->set_flashdata('danger', lang('not_found'));
                redirect('login/register');
            }
            $data_user = [
                'phone' => $this->post('phone', $saved->phone),
                'password_default' => $this->post('password_default', $model->password_default),
                'status' => $this->post('status', $model->status)
            ];
            $data_profile = [
                'name' => $this->post('name', $saved->name),
                'location' => $this->post('location', $saved->location),
                'card_name' => $this->post('card_name', $saved->card_name),
                'info_tambahan' => $this->post('info_tambahan', $saved->info_tambahan),
                'email' => $this->post('email', $saved->email),
                'optic' => $this->post('optic', $saved->optic),
                'province' => $this->post('province', $saved->province),
                'city' => $this->post('city', $saved->city),
                'district' => $this->post('district', $saved->district),
                'sub_district' => $this->post('sub_district', $saved->sub_district),
                'poscode' => $this->post('poscode', $saved->poscode),
                'address' => $this->post('address', $saved->address),
                'pax' => $this->post('pax', $saved->pax),
                'pax_name' => $this->post('pax_name', $saved->pax_name),
                'pax_email' => $this->post('pax_email', $saved->pax_email),
                'pax_phone' => $this->post('pax_phone', $saved->pax_phone),
                'table' => $this->post('table', $saved->table),
                'seat' => $this->post('seat', $saved->seat),
                'privacy' => $this->post('privacy'),
                'inform' => $this->post('inform'),
                'main_course' => $this->post('main_course', $saved->main_course),
                'alergy' => $this->post('alergy', $saved->alergy)
            ];
        }
        $roles = [User_model::LOGIN_TYPE_VISITOR];
        // validate data
        $validate = $this->validate_form([
            'name' => [
                'rules' => 'trim|required',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('name')])
                ],
            ],
            'phone' => [
                'rules' => 'trim|required',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('phone')])
                ],
            ],
            'email' => [
                'rules' => 'trim|required',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('email')])
                ],
            ],
            'optic' => [
                'rules' => 'trim|required',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('optic')])
                ],
            ],
            'province' => [
                'rules' => 'trim',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('province')])
                ],
            ],
            'city' => [
                'rules' => 'trim',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('city')])
                ],
            ],
            'pax' => [
                'rules' => 'trim',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('pax')])
                ],
            ],
            'privacy' => [
                'rules' => 'trim|required',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('privacy')])
                ],
            ],
            'inform' => [
                'rules' => 'trim',
                'message' => [
                    'trim' => ''
                ],
            ],
            'info_tambahan' => [
                'rules' => 'trim',
                'message' => [
                    'trim' => ''
                ],
            ],
//            'password' => [
//                'rules' => 'trim|required',
//                'message' => [
//                    'required' => lang('cannot_be_null', ['{name}' => lang('password')])
//                ],
//            ],
//            'confirm_password' => [
//                'rules' => 'trim|required|matches[password]',
//                'message' => [
//                    'required' => lang('cannot_be_null', ['{name}' => lang('confirm_password')]),
//                    'matches' => lang('not_match', ['{name}' => lang('confirm_password'), '{match}' => lang('password')]),
//                ],
//            ]
            ], false);
        // processing data
        if ($validate === true) { // must exact true type data
            Ci::helpers(['mail', 'hash']);
            Ci::library('qr2');
            // sanitize phone
            $data_user['username'] = phone($data_user['phone']);
            $exists = User_model::get_dbo()->where('username', $data_user['username'])->first();
            $exists2 = User_profile_model::get_dbo()->where('email', $data_profile['email'])->first();
            if ($exists || $exists2) {
                $this->session->set_flashdata('danger', lang('phone_exists'));
            } elseif ($data_profile['pax'] == 2 && (!$data_profile['pax_name'] || !$data_profile['pax_phone'])) {
                $this->session->set_flashdata('danger', 'Harap untuk mengisi Nama Pesera 2 & Nomor Ponsel 2 untuk menghadiri acara lebih dari satu orang.');
            } else {
                Capsule::beginTransaction();
                $model = $this->_bikin_id_2($data_user, $data_profile);
                if (!$model) {
                    Capsule::rollback();
                } else {
                    if ($data_profile['pax'] == 2) {
                        $data_user_2 = array_merge($data_user, [
                            'phone' => phone($data_profile['pax_phone']),
                        ]);
                        $data_profile_2 = array_merge($data_profile, [
                            'name' => $data_profile['pax_name'],
                            'email' => $data_profile['pax_email'],
                            'pax_name' => null,
                            'pax_email' => null,
                            'pax_phone' => null,
                        ]);
                        $user2 = User_model::get_dbo()->where('username', $data_user_2['phone'])->first();
                        if (!$user2) {
                            $model2 = $this->_bikin_id_2($data_user_2, $data_profile_2);
                            if (!$model2) {
                                $this->session->set_flashdata('danger', 'Gagal menympan data peserta kedua.');
                                Capsule::rollback();
                            } else {
                                // Commit data
                                Capsule::commit();
                                $this->_auto_login($model);
                                $this->session->set_flashdata('success', lang('register_success'));
                                redirect('dashboard/profile');
                            }
                        } else {
                            $this->session->set_flashdata('danger', 'Nomor ponsel peserta kedua telah terdaftar.');
                            Capsule::rollback();
                        }
                    } else {
                        // langsung commit kalau pax cuma 1Commit data
                        Capsule::commit();
                        $this->_auto_login($model);
                        $this->session->set_flashdata('success', lang('register_success'));
                        redirect('dashboard/profile');
                    }
                }
            }
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }
//        // get master role
//        $role_list = Role_model::get_dbo()->get();

        Ci::view(__METHOD__, [
            'data' => array_merge($data_profile, $data_user),
            'id' => $id,
            'redir' => $this->get_redir(true), // true = encode url (for display)
            'model' => $model,
            'profile_model' => $profile_model,
            'location' => $location,
            'poscode_select' => $this->post('poscode_select')
//            'role_list' => $role_list
        ]);
    }

    private function _bikin_id_2($data_user, $data_profile) {
        $model = new User_model();
        $profile_model = new User_profile_model();
        // user
        $data_user['username'] = phone($data_user['phone']);
        $exists = User_model::get_dbo()->where('username', $data_user['username'])->first();
        if ($exists) {
            $this->session->set_flashdata('danger', lang('phone_exists'));
            return false;
        } else {
            $data_user['password'] = run_hash('ahmgca');
            $data_user['password_default'] = 'ahmgca';
            $data_user['status'] = 1;
            unset($data_user['phone']);
            $model->save_update($data_user);
            // save identity
            $identity = User_model::generate_identity($model->id);
//            User_model::get_dbo()->where('id', $model->id)->update(['identity' => $identity]);
            // save profile user
            $data_profile['user_id'] = $model->id;
            $data_profile['avatar'] = 'user.png';
            $data_profile['phone'] = $data_user['username'];
            $data_profile['pax_phone'] = phone($data_profile['pax_phone']);
//        $data_profile['phone'] = $data_profile['phone'] ? phone($data_profile['phone']) : null;
            $profile_model->save_update($data_profile);
            // save role
            User_role_model::arrange($model->id, [User_model::LOGIN_TYPE_VISITOR]);
            // generate qr image
            $qr = new Qr2;
            // generate qr image
            $qr->with_logo($identity);
            // generate share image
            $qr->with_border($identity, $data_profile['name'], $data_profile['optic'], '0' . $data_profile['phone']);

            send_mail([
                'to' => $data_profile['email'],
                'subject' => 'AHM Group Customer Appreciation - Registrasi',
                'message' => Ci::partials('email/registration_code', ['user' => ['identity' => $identity, 'id' => $model->id], 'profile' => $data_profile])
            ]);
            // autologin
            $token = md5(time());
            $model->login_token = $token;
            $model->identity = $identity;
            $model->save();
            return $model;
        }
    }

    public function register_success() {
        Ci::view(__METHOD__);
    }

    public function find_user($location = 'general') {
        $data = [
            'phone' => $this->post('phone'),
        ];

        $validate = $this->validate_form(['phone'], false);

        if ($validate === true) {
            $phone = $data['phone'] ? phone($data['phone']) : null;
            $user = User_model::get_dbo()->where('username', $phone)->first();
            if ($user) {
                $this->_auto_login($user);
                redirect('dashboard/profile');
            } else {
                $model = User_data_model::get_dbo()->where('phone', $phone)->first();
                if ($phone && $model) {
                    $this->session->set_flashdata('success', 'Mohon melengkapi data pada formulir dibawah ini.');
                    redirect('login/register/' . strtolower($model->location) . '/' . $model->id);
                } else {
                    $this->session->set_flashdata('error', 'No Telepon tidak tersedia.');
                }
            }
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }

        Ci::view(__METHOD__, ['data' => $data, 'redir' => $this->get_redir(true), 'location' => $location]);
    }

    private function _auto_login($model) {
        // autologin
        $token = md5(time());
        $login_types = $model->roles->pluck('login_type')->toArray();
        $model->login_token = $token;
        $model->save();
        $this->session->set_userdata(TOKEN_SESSION, [
            'user' => $model->toArray() + ['profile' => $model->profile->toArray()],
            'profile' => $model->profile->toArray(),
            'permissions' => $model->get_permissions()->pluck('name', 'id')->toArray(),
            'token' => $token,
            'login_types' => $login_types
        ]);
    }

    public function change() {
        if (!$this->user) {
            redirect('login');
        }
        $model = Ci::model('model_usrmaster');
        $model->data([
            'newPassword' => [
                'data' => Ci::post('newPassword'),
                'rules' => 'trim|required',
                'label' => 'lang:newPassword'
            ],
            'confirmPassword' => [
                'data' => Ci::post('confirmPassword'),
                'rules' => 'trim|required|matches[newPassword]',
                'label' => 'lang:confirmPassword'
            ],
        ]);
        if ($model->validate() && $model->change_password($this->user)) {
            redirect('home/index');
        } else {
            if (($error = validation_errors())) {
                $this->session->set_flashdata('error', $error);
            }
            Ci::view(__METHOD__, ['model' => $model]);
        }
    }

    public function logout() {
        $user = new User_model();
        $user->logout($this->user['user']['id']);
        redirect('login');
    }

    public function forgot() {
        $model = Ci::model('model_usrmaster');
        $model->data([
            'userEmail' => Ci::post('userEmail')
        ]);
        if ($model->validate() && $model->send_forgot(1)) {
            redirect('login');
        } else {
            if (($error = validation_errors())) {
                $this->session->set_flashdata('error', $error);
            }
            Ci::view(__METHOD__, ['model' => $model]);
        }
    }

    public function reset($token = null) {
        $model = Ci::model('model_usrmaster');
        if (!$model->fill($model->find_by_reset_token($token))) {
            redirect('login');
        }

        $model->data([
            'newPassword' => [
                'data' => Ci::post('newPassword'),
                'rules' => 'trim|required',
                'label' => 'lang:newPassword'
            ],
            'confirmPassword' => [
                'data' => Ci::post('confirmPassword'),
                'rules' => 'trim|required|matches[newPassword]',
                'label' => 'lang:confirmPassword'
            ]
        ]);
        if ($model->validate() && $model->reset_password(1)) {
            redirect('login');
        } else {
            if (($error = validation_errors())) {
                $this->session->set_flashdata('error', $error);
            }
            Ci::view(__METHOD__, ['model' => $model]);
        }
    }

    public function ajax_poscode_list() {
        $keyword = $this->get('search');
        if ($keyword) {
            $poscodes = Poscode_model::get_dbo()->where('code', 'LIKE', $keyword . '%')->get();
        } else {
            $poscodes = Poscode_model::get_dbo()->get();
        }
        $return = [
            'results' => [],
            'pagination' => ['more' => true]
        ];
        if ($poscodes->count() > 0) {
            foreach ($poscodes as $poscode) {
                $return ['results'][] = [
                    'id' => $poscode->id,
                    'text' => $poscode->code . '(' . $poscode->sub_district . ')'
                ];
            }
        }
        exit(json_encode($return));
    }

    public function ajax_poscode_detail() {
        $id = $this->post('id');
        $poscode = Poscode_model::get_dbo()->where('id', $id)->first();
        if ($poscode) {
            exit(json_encode([
                'success' => 1,
                'data' => $poscode->toArray(),
            ]));
        } else {
            exit(json_encode([
                'success' => 2,
                'msg' => 'Data tidak dapat ditemukan.'
            ]));
        }
    }

}
