<?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 User_data
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class User_data extends MY_Controller {

    public $base = 'user-data/index';

    public function __construct() {
        parent::__construct();
        $this->load->helper(['form', 'pagination', 'slug']);
    }

    public function index($pages = 1) {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_LIST);
        $order = $this->get('order', 'user_data.id');
        $query = User_data_model::get_dbo();

        $query_pagination = query_pagination($query, [
            'per_page' => $this->get('show', 20),
            'pages' => $pages,
            'order' => $order,
            'keyword' => $this->get('keyword'),
            'search_field' => ['user_data.phone', 'user_data.name', 'user_data.optic', 'user_data.pax', 'user_data.email'],
            'uri_segment' => 3,
            'base_url' => base_url($this->base),
        ]);

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

    public function create() {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_CREATE);
        $model = new User_data_model();
        $data = [
            'name' => $this->post('name'),
            'phone' => $this->post('phone'),
            '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'),
            'status' => $this->post('status')
        ];

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

        if ($validate === true) {
            Capsule::beginTransaction();
            $data['phone'] = phone($data['phone']);
            $model->save_update($data);
            Capsule::commit();
            $this->session->set_flashdata('success', 'Tambah data berhasil, Nama: ' . $model->name);
            redirect($this->get_redir());
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }
        Ci::view(__METHOD__, [
            'data' => $data,
            'model' => $model,
            'redir' => $this->get_redir(true),
            'user_absen' => User_model::get_dropdown_by_role(2)
        ]);
    }

    public function update($id = null) {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_UPDATE);
        $model = $this->_find($id);

        $data = [
            'name' => $this->post('name', $model->name),
            'phone' => $this->post('phone', $model->phone),
            'location' => $this->post('location', $model->location),
            'card_name' => $this->post('card_name', $model->card_name),
            'info_tambahan' => $this->post('info_tambahan', $model->info_tambahan),
            'email' => $this->post('email', $model->email),
            'optic' => $this->post('optic', $model->optic),
            'province' => $this->post('province', $model->province),
            'city' => $this->post('city', $model->city),
            'district' => $this->post('district', $model->district),
            'sub_district' => $this->post('sub_district', $model->sub_district),
            'poscode' => $this->post('poscode', $model->poscode),
            'address' => $this->post('address', $model->address),
            'pax' => $this->post('pax', $model->pax),
            'pax_name' => $this->post('pax_name', $model->pax_name),
            'pax_email' => $this->post('pax_email', $model->pax_email),
            'pax_phone' => $this->post('pax_phone', $model->pax_phone),
            'status' => $this->post('status', $model->status)
        ];

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

        if ($validate === true) {
            Capsule::beginTransaction();
            $data['phone'] = phone($data['phone']);
            $model->save_update($data);
            Capsule::commit();
            $this->session->set_flashdata('success', 'Ubah data berhasil, Nama: ' . $model->name);
            redirect($this->get_redir());
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }

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

    public function delete($id = null) {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_DELETE);
        $model = $this->_find($id);
        Capsule::beginTransaction();
        // delete absen
        $model->delete();
        // commit
        Capsule::commit();
        // result
        $this->session->set_flashdata('success', 'Hapus data berhasil, Nama: ' . $model->name);
        redirect($this->get_redir());
    }

    public function import() {
        $this->load->library('ci_spreadsheet');
        $this->load->helper('hash');
        // reading
        $tmp = isset($_FILES['file']['tmp_name']) ? $_FILES['file']['tmp_name'] : null;
        $data = $this->ci_spreadsheet->read($tmp, ['calculate' => true]);
        // filtering
        $filtered = array_filter($data, function($row) {
            return $row['A'] != 'SID' && (!empty($row['B']) && !empty($row['C']) && !empty($row['D']));
        });
        // processing
        Capsule::beginTransaction();
        if ($filtered) {
            $batch = [];
            foreach ($filtered as $res) {
                $res['B'] = phone($res['B']);
                $exists = $this->_get_user_from_excel($res);;
                if ($exists) {
                    $exists->phone = trim($res['B']);
                    $exists->name = trim($res['C']);
                    $exists->location = trim($res['D']);
                    $exists->card_name = trim($res['E']);
                    $exists->info_tambahan = trim($res['F']);
                    $exists->email = trim($res['G']);
                    $exists->optic = trim($res['H']);
                    $exists->province = trim($res['I']);
                    $exists->city = trim($res['J']);
                    $exists->district = trim($res['K']);
                    $exists->sub_district = trim($res['L']);
                    $exists->poscode = trim($res['M']);
                    $exists->address = trim($res['N']);
                    $exists->pax = trim($res['O']);
                    $exists->pax_name = trim($res['P']);
                    $exists->pax_phone = trim($res['Q']);
                    $exists->pax_email = trim($res['R']);
                    $exists->save();
                } else {
                    $batch[] = [
                        'phone' => phone(trim($res['B'])),
                        'name' => trim($res['C']),
                        'location' => trim($res['D']),
                        'card_name' => trim($res['E']),
                        'info_tambahan' => trim($res['F']),
                        'email' => trim($res['G']),
                        'optic' => trim($res['H']),
                        'province' => trim($res['I']),
                        'city' => trim($res['J']),
                        'district' => trim($res['K']),
                        'sub_district' => trim($res['L']),
                        'poscode' => trim($res['M']),
                        'address' => trim($res['N']),
                        'pax' => trim($res['O']),
                        'pax_name' => trim($res['P']),
                        'pax_phone' => trim($res['Q']),
                        'pax_email' => trim($res['R']),
                    ];
                }
            }
            if ($batch) {
                User_data_model::insert($batch);
            }
        }
        // Commit data
        Capsule::commit();
        $this->session->set_flashdata('success', 'Import data selesai');
        redirect($this->get_redir());
    }

    private function _get_user_from_excel($row) {
        $e_user = isset($row['B']) && !empty($row['B']) ? User_data_model::get_dbo()->where('phone', $row['B'])->first() : null;
        if (!$e_user) {
            // coba sekali lgi langsung pake idnya
            $e_user = isset($row['A']) && !empty($row['A']) ? User_data_model::get_dbo()->where('id', trim($row['A']))->first() : null;
        }
        return $e_user;
    }

    public function excel() {
        $this->load->library('ci_spreadsheet');
        $spreadsheet = new Ci_spreadsheet();
        // sheet 1
        $sheet1 = [
            [
                'SID', 'Phone', 'Complete Name', 'Location', 'Card Name',
                'Other Info', 'Email', 'Optic Name', 'Province', 'City',
                'District', 'Sub District', 'Pos Code', 'Address', 'Pax',
                'Pax Name', 'Pax Phone', 'Pax Email'
            ]
        ];
        $users = User_data_model::get_dbo()->get();
        if ($users->count() > 0) {
            foreach ($users as $k => $user) {
                $sheet1[] = [
                    $user->id,
                    $user->phone,
                    $user->name,
                    $user->location,
                    $user->card_name,
                    $user->info_tambahan,
                    $user->email,
                    $user->optic,
                    $user->province,
                    $user->city,
                    $user->district,
                    $user->sub_district,
                    $user->poscode,
                    $user->address,
                    $user->pax,
                    $user->pax_name,
                    $user->pax_phone,
                    $user->pax_email
                ];
            }
        }
        $sheet1_obj = $spreadsheet->prepare_user_data($spreadsheet->getActiveSheet(), [// createSheet()
            'num_row' => count($sheet1),
            'title' => 'Daftar Peserta Master'
        ]);
        $sheet1_obj->fromArray($sheet1);
        // generate
        $spreadsheet->generate('Master_Peserta_' . date('Y-m-d'));
        exit;
    }

    public function email($id = null) {
        $model = $this->_find($id);
        if (!$model->email) {
            $this->session->set_flashdata('danger', 'User tidak memiliki email');
            redirect($this->get_redir());
        }
        $emails = explode(';', $model->email);
        if ($emails) {
            $results = [];
            $this->load->helper('mail');
            foreach ($emails as $email) {
                $results[] = send_mail([
                    'to' => $email,
                    'subject' => 'Varilux XR Series Product Launch - Event Invitation',
                    'message' => Ci::partials('email/invitation', ['model' => $model])
                ]);
            }
            if (!in_array(false, $results)) {
                $model->status = User_data_model::STATUS_MAIL_SENT;
            } else {
                $model->status = User_data_model::STATUS_MAIL_FAILURE;
            }
            $model->updated_at = date('Y-m-d H:i:s');
            $model->updated_by = $this->user['user']['id'];
            $model->save();
        }
        $this->session->set_flashdata('success', 'Email terkirim');
        redirect($this->get_redir());
    }

    protected function _delete_all($ids) {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_DELETE);
        Capsule::beginTransaction();
        // delete user absen
        User_data_model::get_dbo()->whereIn('id', $ids)->delete();
        // commit
        Capsule::commit();
        // result
        $this->session->set_flashdata('success', 'Hapus data berhasil');
        redirect($this->get_redir());
    }

    private function _find($id = null) {
        $model = User_data_model::get_dbo()->where('id', $id)->first();
        if (!$model || !$id) {
            $this->session->set_flashdata('danger', 'Data tidak ditemukan');
            redirect($this->base);
        }
        return $model;
    }

}
