<?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 DB;

/**
 * Description of Doorprize
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Doorprize extends MY_Controller {

    public $base = 'doorprize/index';

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

    public function index($pages = 1) {
//              $this->granted_backoffice(User_model::ACCESS_KELAS_LIST);
        $order = $this->get('order', 'doorprize.id');
        $query = Doorprize_model::get_dbo('doorprize')
            ->select('doorprize.*')
            ->selectRaw('COUNT(`user_doorprize`.`user_id`) as `count_user`')
            ->join('user_doorprize', 'doorprize.id', '=', 'user_doorprize.doorprize_id', 'left')
            ->groupBy('doorprize.id');
        // ribet asli
        if (strpos($order, 'user_doorprize.user_id') !== false) {
            $direction = substr($order, 0, 1) == '-' ? 'DESC' : 'ASC';
            $query->orderByRaw('COUNT(`user_doorprize`.`user_id`) ' . $direction);
        }

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

        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_KELAS_CREATE);
        $data = [
            'nama' => $this->post('nama'),
            'slug' => $this->post('slug'),
            'location' => 'general',
            'gambar' => '',
            'total' =>$this->post('total'),
        ];

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

        if ($validate === true) {
            $model = new Doorprize_model();
            $data['slug'] = slug($data['nama']);
            Ci::helper('upload');
            $gambar = do_upload('gambar', [
                'allowed_types' => 'gif|jpg|jpeg|png|tiff|mp4|mov|wmv|avi|flv|mkv|mpeg',
            ]);
            if (!$gambar['error']) {
                $data['gambar'] = $gambar['data']['file_name'];
            }
            $model->save_update($data);
            $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,
            'redir' => $this->get_redir(true),
        ]);
    }

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

        $data = [
            'nama' => $this->post('nama', $model->nama),
            'slug' => $this->post('slug', $model->slug),
//            'location' => $this->post('location', $model->location),
            'gambar' => $model->gambar,
            'total' =>$this->post('total', $model->total),
        ];

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

        if ($validate === true) {
            $data['slug'] = $data['slug'] ? slug($data['slug']) : slug($data['nama']);
            Ci::helper('upload');
            $gambar = do_upload('gambar', [
                'allowed_types' => 'gif|jpg|jpeg|png|tiff|mp4|mov|wmv|avi|flv|mkv|mpeg',
                'max_size' => 2000000,
            ]);
            if (!$gambar['error']) {
                if (is_file(UPLOAD_PATH . $data['gambar'])) {
                    unlink(UPLOAD_PATH . $data['gambar']);
                }
                $data['gambar'] = $gambar['data']['file_name'];
            }
            $model->save_update($data);
            $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,
            'redir' => $this->get_redir(true),
//            'kelas' => Kelas_model::get_dropdown(),
//            'sesi' => Sesi_model::get_dropdown()
        ]);
    }

    public function qr($id = null) {
        $this->load->library('qr');
        $doorprize = $this->_find($id);
        $qrfile = QRPATH . $doorprize->slug . '.png';
        $url = base_url('../doorprize/index/' . $doorprize->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() {
        $doorprize = Doorprize_model::get_dbo()->get();
        $html = Ci::partials(__METHOD__, ['doorprize' => $doorprize]);
//        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 delete($id = null) {
//              $this->granted_backoffice(User_model::ACCESS_KELAS_DELETE);

        $model = $this->_find($id);
        $model->delete();
        $this->session->set_flashdata('success', 'Hapus data berhasil, Nama: ' . $model->nama);
        redirect($this->get_redir());
    }

    public function import() {
        $this->load->library('ci_spreadsheet');
        $this->load->helper('slug');
        // 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 isset($row['B']) && !empty($row['B']) && $row['B'] != 'nama' && $row['B'] != 'Name' && $row['A'] != 'SID';
        });
        // processing
        DB::beginTransaction();
        if ($filtered) {
            foreach ($filtered as $res) {
                $doorprize = $this->_get_doorprize_from_excel($res);
                $doorprize_data = [];
                if (!$doorprize) {
                    // save user data
                    $doorprize = new Doorprize_model();
                    $doorprize_data = [
                        'nama' => $res['B'],
                        'slug' => slug(trim(strtolower($res['B']))),
                        'status' => User_model::STATUS_ACTIVE,
                    ];
                }
                if ($res['C']) {
                    $doorprize_data['gambar'] = $res['C'];
                }
                $doorprize->save_update($doorprize_data);
            }
        }
        // Commit data
        DB::commit();
        $this->session->set_flashdata('success', 'Import data selesai');
        redirect($this->get_redir());
    }

    private function _get_doorprize_from_excel($row) {
        $e_user = isset($row['B']) && !empty($row['B']) ? Doorprize_model::get_dbo()->where('nama', trim(strtolower($row['B'])))->first() : null;
        if (!$e_user) {
            // coba sekali lgi langsung pake idnya
            $e_user = isset($row['A']) && !empty($row['A']) ? Doorprize_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', 'Doorprize', 'Gambar']
        ];
        $absen = Doorprize_model::get_dbo('doorprize')
            ->orderBy('doorprize.id', 'ASC')
            ->get();
        if ($absen->count() > 0) {
            foreach ($absen as $k => $data) {
                $sheet1[] = [
                    $data->id, $data->nama, $data->gambar
                ];
            }
        }
        $sheet1_obj = $spreadsheet->prepare_doorprize($spreadsheet->getActiveSheet(), [// createSheet()
            'num_row' => count($sheet1),
            'title' => 'Master Doorprize'
        ]);
        $sheet1_obj->fromArray($sheet1);
        // generate
        $spreadsheet->generate('Doorprize_' . date('Y-m-d'));
        exit;
    }

    protected function _delete_all($ids) {
//              $this->granted_backoffice(User_model::ACCESS_KELAS_DELETE);

        Doorprize_model::get_dbo()->whereIn('id', $ids)->delete();
        redirect($this->get_redir());
    }

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

}
