<?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');

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

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

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

    public function index($doorprize_id = 'all', $pages = 1) {
//        $this->granted_backoffice(User_model::ACCESS_KELOMPOK_LIST);
        $doorprize = null;
        if ($doorprize_id != 'all') {
            $doorprize = Doorprize_model::get_dbo()->where('id', $doorprize_id)->first();
            if (!$doorprize) {
                $this->session->set_flashdata('danger', 'Data tidak dapat ditemukan');
                redirect('doorprize');
            }
        }
        $query = User_doorprize_model::get_dbo('user_doorprize')
                ->select('user_doorprize.*', 'user_profile.name AS nama_anggota', 'doorprize.nama AS nama_doorprize')
                ->join('user_profile', 'user_doorprize.user_id', '=', 'user_profile.user_id', 'left')
                ->join('doorprize', 'user_doorprize.doorprize_id', '=', 'doorprize.id', 'left');
        if ($doorprize_id != 'all') {
            $query->where('user_doorprize.doorprize_id', $doorprize->id);
        }
        $query_pagination = query_pagination($query, [
            'per_page' => $this->get('show', 20),
            'pages' => $pages,
            'order' => $this->get('order', '-user_doorprize.created_at'),
            'keyword' => $this->get('keyword'),
            'search_field' => ['doorprize.nama', 'user_profile.name'],
            'uri_segment' => 4,
            'base_url' => base_url('user-doorprize/index/' . $doorprize_id),
        ]);

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

    public function create($doorprize_id = null) {
//        $this->granted_backoffice(User_model::ACCESS_KELOMPOK_CREATE);

        $doorprize = Doorprize_model::get_dbo()->where('id', $doorprize_id)->first();
        if (!$doorprize) {
            $this->session->set_flashdata('danger', 'Data tidak dapat ditemukan');
            redirect('doorprize');
        }

        $data = [
            'doorprize_id' => $doorprize->id,
            'user_id' => $this->post('user_id')
        ];
        $validate = $this->validate_form(['user_id'], false);

        if ($validate === true) {
            $model = new User_doorprize_model();
            $model->save_update($data);
            $this->session->set_flashdata('success', 'Tambah data berhasil');
        } elseif ($validate[static::$field_status] === static::CODE_INVALID_PARAMETER) {
            $this->_show_alert($validate);
        }
        redirect($this->get_redir());
    }

    public function ajax_anggota($doorprize_id = null) {
        $search = $this->get('search');
        $anggota_list = User_doorprize_model::get_dbo()->where('doorprize_id', $doorprize_id)->get()->pluck('user_id')->toArray();
        $anggota_query = User_profile_model::get_dbo();

        if ($search) {
            $anggota_query->where(function($query) use($search) {
                $query->orWhere('name', 'like', '%' . $search . '%');
            });
        }
        if ($anggota_list) {
            $anggota_query->whereNotIn('user_id', $anggota_list);
        }
        $anggota = $anggota_query->get();
        $return = [
            'results' => [],
            'pagination' => [
                'more' => false
            ],
        ];
        if ($anggota) {
            foreach ($anggota as $res) {
                $txt = $res->name;
                $html = $txt;
                $return['results'][] = [
                    'id' => $res->user_id,
                    'text' => $txt,
                    'html' => $html,
                ];
            }
        }
        exit(json_encode($return));
    }
    
    public function excel() {
        $this->load->library('ci_spreadsheet');
        $spreadsheet = new Ci_spreadsheet();
        // sheet 1
        $sheet1 = [
            ['No', 'Doorprize', 'Link Doorprize']
        ];
        $absen = Doorprize_model::get_dbo('doorprize')
                ->orderBy('doorprize.id', 'ASC')
                ->get();
        if ($absen->count() > 0) {
            foreach ($absen as $k => $data) {
                $sheet1[] = [
                    $k + 1, $data->nama, base_url('../doorprize/index/' . $data->slug)
                ];
            }
        }
        $sheet1_obj = $spreadsheet->prepare_doorprize($spreadsheet->getActiveSheet(), [// createSheet()
            'num_row' => count($sheet1),
            'title' => 'Master Doorprize'
        ]);
        $sheet1_obj->fromArray($sheet1);
        // sheet 2
        $sheet2 = [
            ['No', 'Doorprize', 'Nama Peserta', 'Tanggal']
        ];
        $anggota = User_doorprize_model::get_dbo('user_doorprize')
                ->select('user_doorprize.*', 'doorprize.nama as nama_doorprize', 'user_profile.name as nama_user')
                ->leftJoin('user_profile', 'user_doorprize.user_id', '=', 'user_profile.user_id')
                ->leftJoin('doorprize', 'user_doorprize.doorprize_id', '=', 'doorprize.id')
                ->orderBy('user_doorprize.created_at', 'DESC')
                ->get();
        if ($anggota->count() > 0) {
            foreach ($anggota as $k => $data) {
                $sheet2[] = [
                    $k+1, $data->nama_doorprize, $data->nama_user,
                    $spreadsheet->excel_time($data->created_at),
                    $spreadsheet->excel_time($data->created_at)
                ];
            }
        }
        $sheet2_obj = $spreadsheet->prepare_doorprize_detail($spreadsheet->createSheet(), [// createSheet()
            'num_row' => count($sheet2),
            'title' => 'History Doorprize'
        ]);
        $sheet2_obj->fromArray($sheet2);
        // generate
        $spreadsheet->generate('Doorprize_' . date('Y-m-d'));
        exit;
    }

    public function delete($doorprize_id = null, $user_id = null) {
//        $this->granted_backoffice(User_model::ACCESS_KELOMPOK_DELETE);
        $model = $this->_find($doorprize_id, $user_id);
        if (!$model) {
            $this->session->set_flashdata('danger', 'Data tidak dapat ditemukan');
        } else {
            User_doorprize_model::get_dbo()->where_key($doorprize_id, $user_id)->delete();
            $this->session->set_flashdata('success', 'Hapus data berhasil');
        }
        redirect($this->get_redir());
    }

    protected function _delete_all($ids) {
//        $this->granted_backoffice(User_model::ACCESS_KELAS_DELETE);
        if ($ids) {
            foreach ($ids as $raw_id) {
                $part_id = explode('|', $raw_id);
                $doorprize_id = isset($part_id[0]) ? $part_id[0] : null;
                $user_id = isset($part_id[1]) ? $part_id[1] : null;
                if (!$doorprize_id || !$user_id) {
                    continue;
                }
                User_doorprize_model::get_dbo()->where_key($doorprize_id, $user_id)->delete();
            }
        }
        redirect($this->get_redir());
    }

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

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

}
