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

    public $base = 'absen/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', 'absen.id');
        $query = Absen_model::get_dbo('absen')
                ->select('absen.*')
                ->selectRaw('COUNT(`visitor_absen`.`visitor_id`) as `count_visitor`')
                ->join('visitor_absen', 'absen.id', '=', 'visitor_absen.absen_id', 'left')
                ->groupBy('absen.id');
        // ribet asli
        if (strpos($order, 'visitor_absen.visitor_id') !== false) {
            $direction = substr($order, 0, 1) == '-' ? 'DESC' : 'ASC';
            $query->orderByRaw('COUNT(`visitor_absen`.`visitor_id`) ' . $direction);
        }

        $query_pagination = query_pagination($query, [
            'per_page' => $this->get('show', 20),
            'pages' => $pages,
            'order' => $order,
            'keyword' => $this->get('keyword'),
            'search_field' => ['absen.nama', 'absen.keterangan'],
            'uri_segment' => 3,
            '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 Absen_model();
        $data = [
            'nama' => $this->post('nama'),
            'slug' => $this->post('slug'),
            'tipe' => $this->post('tipe'),
            'keterangan' => $this->post('keterangan'),
            'syarat' => $this->post('syarat'),
//             'location' => $this->post('location')
        ];
        $user_absen = $this->post('user_absen');

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

        if ($validate === true) {
            Capsule::beginTransaction();
            $data['slug'] = slug($data['nama']);
            $data['syarat'] = serialize($data['syarat']);
            $model->save_update($data);
            User_absen_model::arrange($model->id, $user_absen);
            Capsule::commit();
            $this->session->set_flashdata('success', 'Tambah data berhasil, Nama: ' . $model->nama);
            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 = [
            'nama' => $this->post('nama', $model->nama),
            'slug' => $this->post('slug', $model->slug),
            'tipe' => $this->post('tipe', $model->tipe),
            'keterangan' => $this->post('keterangan', $model->keterangan),
            'syarat' => $this->post('syarat', $model->syarat),
//            'location' => $this->post('location', $model->location)
        ];
        $user_absen = $this->post('user_absen');

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

        if ($validate === true) {
            Capsule::beginTransaction();
            $data['slug'] = $data['slug'] ? slug($data['slug']) : slug($data['nama']);
            $data['syarat'] = serialize($data['syarat']);
            $model->save_update($data);
            User_absen_model::arrange($model->id, $user_absen);
            Capsule::commit();
            $this->session->set_flashdata('success', 'Ubah data berhasil, Nama: ' . $model->nama);
            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 qr($id = null) {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_QR);
        $this->load->library('qr');
        $absen = $this->_find($id);
        $qrfile = QRPATH . $absen->slug . '.png';
        $url = base_url('../absen/index/' . $absen->slug);
        if (!is_file($qrfile)) {
            Qr::png($url, $qrfile, QR_ECLEVEL_H, 10, 4);
        }
        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($qrfile) . '"');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . filesize($qrfile));    // provide file size
        readfile($qrfile);       // push it out
        exit;
    }

    public function generate_qr() {
        $this->granted_backoffice(User_model::ACCESS_ABSEN_QR_LIST);
        $absen = Absen_model::get_dbo()->get();
        $html = Ci::partials(__METHOD__, ['absen' => $absen]);
//        echo $html;
//        exit;
        $mpdf = new \Mpdf\Mpdf();

        // Write some HTML code:
//        $mpdf->SetHTMLHeader($header, 'E', true);
//        $mpdf->SetHTMLHeader($header, 'O', true);
//        $mpdf->SetHTMLFooter($footer, 'E');
//        $mpdf->SetHTMLFooter($footer, 'O');
        $mpdf->AddPage('P', // L - landscape, P - portrait 
                '', '', '', '',
                8, // margin_left
                8, // margin right
                8, // margin top
                8, // margin bottom
                0, // margin header
                0); // margin footer
        $mpdf->WriteHTML($html);
        $mpdf->use_kwt = true;
        $mpdf->shrink_tables_to_fit = 1;
        // Output a PDF file directly to the browser
        $mpdf->Output('QR Code.pdf', 'I');
        exit;
    }

    public function excel($id = null) {
        $this->load->library('ci_spreadsheet');
        $spreadsheet = new Ci_spreadsheet();
        $model = $this->_find($id);
        $visitors = Visitor_absen_model::get_dbo()->where('absen_id', $model->id)->orderBy('created_at', 'ASC')->get();
        // sheet 1
        $sheet1 = [
            [''],
            [
                '', $model->nama, '', '', $visitors->count() . ' Data',
            ],
            [''],
            [
                'No', 'Nama', 'Optic', 'Tanggal'
            ]
        ];
        if ($visitors->count() > 0) {
            foreach ($visitors as $k => $visitor) {
                $sheet1[] = [
                    $k + 1, $visitor->visitor->profile->name,
                    $visitor->visitor->profile->optic,
                    date('d-m-Y', strtotime($visitor->created_at)),
                    date('H:i', strtotime($visitor->created_at))
                ];
            }
        }
        $sheet1_obj = $spreadsheet->prepare_absen($spreadsheet->getActiveSheet(), [// createSheet()
            'num_row' => count($sheet1),
            'title' => 'Histori Absen'
        ]);
        $sheet1_obj->fromArray($sheet1);
        // generate
        $spreadsheet->generate('History_absen');
        exit;
    }

    public function ajax_syarat_form($id = null) {
        echo Ci::partials('absen/_syarat_form', [
            'id' => $id,
            'value' => $this->post('value')
        ]);
        exit;
    }

    public function ajax_syarat_modal($id = null) {
        $model = Absen_model::get_dbo()->get();
        echo Ci::partials('absen/_syarat_modal', ['id' => $id, 'model' => $model]);
        exit;
    }

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

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

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

}
