<?php

/*
 * *************************************************
 * Copyright (C) 2021 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 Dashboard
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Dashboard 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 = 'general', $id = null) {
        Ci::set_layout_file('main_dashboard');
//        if ($this->user) {
//            redirect('dashboard/profile');
//        }
        $user_data = User_data_model::get_dbo()->where('id', $id)->first();
        if ($user_data) {
            $user = User_model::get_dbo()->where('username', $user_data->phone)->first();
            if ($user) {
                $this->_auto_login($user);
                redirect('dashboard/profile');
            }
        }
        Ci::helper('form');
        Ci::view(__METHOD__, ['id' => $id, 'location' => $location]);
    }

    public function apps() {
        Ci::view(__METHOD__, ['hide_banner' => true]);
    }

    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 profile() {
//        Ci::set_layout_file('main_dashboard');
        if (!$this->user) {
            redirect('dashboard/index');
        }

        $user = $this->user['user'];
        $profile = $user['profile'];
        $this->load->library('qr2');
        // generate qr image
        $qr = new Qr2;
        // generate qr image
        $qr->with_logo($user['identity']);
        // generate share image
        $qr->with_border($user['identity'], $profile['name'], $profile['optic'], '0' . $profile['phone']);

        Ci::view(__METHOD__, ['user' => $user, 'profile' => $profile]);
    }

    public function profile2() {
        $this->load->library('qr2');
        // generate qr image
        $qr = new Qr2;
        // generate qr image
        $qr->with_logo('https://kodak.deboer.id/form/index/survey', 'survey');
        // generate share image
        //$qr->with_border($user['identity'], $profile['name'], $profile['optic'], '0' . $profile['phone']);
    }

    public function download($identity = null) {
        $user = User_model::get_dbo()->where('identity', $identity)->where('id', $this->get('uid'))->first();
        $file = $user ? QRPATH . $user->identity . '.png' : null;
        if (!is_file($file) || !$user) {
            echo 'Cannot download QR Code';
        } else {
            header('Pragma: public');   // required
            header('Expires: 0');       // no cache
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Cache-Control: private', false);
            header('Content-Type: image/png');
            header('Content-Disposition: attachment; filename="' . basename($file) . '"');
            header('Content-Transfer-Encoding: binary');
            header('Content-Length: ' . filesize($file));    // provide file size
            readfile($file);       // push it out
        }
        exit;
    }

    public function absen($pages = 1) {
//        Ci::set_layout_file('main_dashboard');
        $this->load->helper(['form', 'pagination', 'slug']);
        if (!$this->user) {
            redirect('login');
        }

        $query = Visitor_absen_model::get_dbo('visitor_absen')
            ->select('visitor_absen.*', 'visitor_profile.name as nama_visitor', 'absen.nama as nama_absen')
            ->leftJoin('absen', 'visitor_absen.absen_id', '=', 'absen.id')
            ->leftJoin('users as visitors', 'visitor_absen.visitor_id', '=', 'visitors.id')
            ->leftJoin('user_profile as visitor_profile', 'visitors.id', '=', 'visitor_profile.user_id')
            ->where('visitor_absen.visitor_id', $this->user['user']['id']);

        $query_pagination = query_pagination($query, [
            'per_page' => $this->get('show', 20),
            'pages' => $pages,
            'order' => $this->get('order', '-visitor_absen.created_at'),
            'keyword' => $this->get('keyword'),
            'search_field' => ['absen.nama'],
            'uri_segment' => 3,
            'base_url' => 'dashboard/absen',
        ]);

        Ci::view(__METHOD__, [
            'user' => $this->user,
            'query_pagination' => $query_pagination,
            'pagination' => create_pagination($query_pagination),
            'redir' => '?redir=' . urlencode(current_url() . url_query())
        ]);
    }

    public function change_profile() {
//        Ci::set_layout_file('main_dashboard');
        if (!$this->user) {
            redirect('login');
        }
        $this->load->helper('form');
        $user = User_model::get_dbo()->where('id', $this->user['user']['id'])->first(); // because stored as array in session

        $profile_model = $user->profile;
        // post data
        $data_user = [
            'username' => $user->username,
//            'old_password' => $this->post('old_password'),
            'new_password' => $this->post('new_password'),
            'confirm_password' => $this->post('confirm_password')
        ];
        $data_profile = [
            'name' => $profile_model->name,
            'email' => $profile_model->email,
            'phone' => $profile_model->phone,
            'optic' => $profile_model->optic,
            'pax' => $profile_model->pax,
            'seat_table' => $profile_model->seat_table
        ];
//        $data_profile = [
//            'name' => $this->post('name', $profile_model->name),
//            'email' => $this->post('email', $profile_model->email),
//            'phone' => $this->post('phone', $profile_model->phone)
//        ];
        $data = array_merge($data_user, $data_profile);
        // validate data
//        $data_validate = [
//            'name' => [
//                'rules' => 'trim|required',
//                'message' => ['required' => lang('%s_reqired')]
//            ],
//            'email' => [
//                'rules' => 'trim|valid_email',
//                'message' => ['valid_email' => lang('%s_not_valid_email')]
//            ]
//        ];
        $data_validate = [];
//        if ($data['old_password']) {
        $data_validate = array_merge($data_validate, [
//                'old_password' => [
//                    'rules' => 'trim|required',
//                    'message' => ['required' => lang('%s_reqired')]
//                ],
            'new_password' => [
                'rules' => 'trim|required',
                'message' => ['required' => lang('%s_reqired')]
            ],
            'confirm_password' => [
                'rules' => 'trim|required|matches[new_password]',
                'message' => [
                    'required' => lang('%s_reqired'),
                    'matches' => lang('%s_not_match')
                ]
            ]
        ]);
//        }
        $validate = $this->validate_form($data_validate, false);
        // prosessing data
        if ($validate === true) {
            $this->load->helper('hash');
            Capsule::beginTransaction();
            // we can save profile information directly
//            $profile_model->save_update($data_profile);
            // checking old password
//            if ($data['old_password']) { // if old_password entered
//                if (run_verify($data['old_password'], $user->password)) {
            $user->save_update([
                'password' => run_hash($data['new_password']),
                'password_default' => ''
            ]);
//                    Capsule::commit();
//                    $this->session->set_flashdata('changed_password', 1);
//                    $this->session->set_flashdata('success', lang('update_profile_success'));
//                    redirect($this->get_redir());
//                } else {
//                    $this->session->set_flashdata('danger', lang('old_password_not_match'));
//                    Capsule::rollback();
//                }
//            } else {
            // assumtion is only change the profile information
            Capsule::commit();
            $this->session->set_flashdata('changed_password', 1);
            $this->session->set_flashdata('success', lang('change_password_success'));
            redirect($this->get_redir());
//            }
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }

        Ci::view(__METHOD__, [
            'user' => $this->user,
            'data' => $data,
            'redir' => $this->get_redir(true), // true = encode url (for display)
            'model' => $user,
            'profile_model' => $profile_model,
        ]);
    }

    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('transitions2022');
            $data_user['password_default'] = 'transitions2022';
            $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' => 'Transitions: The Pulse (Indonesia) - 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 new($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', $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')
            ];
        } 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')
            ];
        }
        $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',
                'message' => [
                    'trim' => '',
                ],
            ],
            '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' => [
                    'trim' => lang('cannot_be_null', ['{name}' => lang('city')])
                ],
            ],
            'privacy' => [
                'rules' => 'trim|required',
                'message' => [
                    'required' => lang('cannot_be_null', ['{name}' => lang('privacy')])
                ],
            ],
            'inform' => [
                'rules' => 'trim',
                'message' => [
                    'trim' => ''
                ],
            ],
            'info_tambahan' => [
                'rules' => 'trim',
                'message' => [
                    'trim' => ''
                ],
            ],
            ], 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
        ]);
    }

}
