<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

//error_reporting('E_ALL ^ E_NOTICE');
class Barcode extends MY_Controller {

    public function __construct() {
        parent::__construct();
        if (!get_license_per('points')) {
            redirect("", "refresh");
        }
        $this->operator_id = $this->session->userdata("operator_id");

        if (get_ap('points_ac', $this->operator_id) == 1) {
            
        } else {
            redirect("", "refresh");
        }
        $this->load->model("points/Barcode_Model");
        $this->load->helper('security');
    }

    public function index($type = "") {
        $data['title'] = $this->lang->line('points');
        //$data['results'] = $this->Barcode_Model->get_barcode($type);
        //pr($data);
        $data['categorys'] = $this->Barcode_Model->get_category('category');
        $data['notes'] = $this->Barcode_Model->get_category('notes');
        $data['type'] = $type;
        $this->load->view("points/barcode/index", $data);
    }

    public function create() {
        if ($this->input->server("REQUEST_METHOD") == "POST") {
            $data = $this->input->post();
            $barcode = $data['barcode'];
            if ($barcode) {
                for ($i = 0; $i < $barcode; $i++) {
                    $scan_code = time() . rand();

                    $scan_url = "scan-" . $scan_code . ".png";
                    $this->load->library('ciqrcode');
                    $params['data'] = base_url('points/user/points/' . $scan_code);
                    $params['level'] = 'H';
                    $params['size'] = 10;
                    $params['savename'] = 'uploads/points/' . $scan_url;
                    $this->ciqrcode->generate($params);
                    $arrray = array(
                        'scan_code' => $scan_code,
                        'student_point' => $data['points'],
                        'notes_id' => $data['notes_id'],
                        'category_id' => $data['category_id'],
                        'barcode' => $scan_url,
                        'barcode_status' => 0
                    );
                    /* pr($arrray);
                      die; */
                    $this->Barcode_Model->save($arrray);
                }
            }
            $this->session->set_flashdata('message', 'Successfully Created');
            redirect('points/barcode', 'refresh');
        }
        $data['title'] = $this->lang->line("add_points");
        $data['category'] = $this->Barcode_Model->get_category('category');
        $data['notes'] = $this->Barcode_Model->get_category('notes');
        //$data['members'] = $this->Barcode_Model->get_tables('admin');
        $this->load->view("points/barcode/create", $data);
    }

    public function edit($id) {
        if ($this->input->server("REQUEST_METHOD") == "POST") {
            $data = $this->input->post();
            $this->Barcode_Model->update($id, $data);
            $this->session->set_flashdata('message', 'Successfully Updated');
            redirect('admin/barcode/', 'refresh');
        }
        $data['title'] = "Edit Barcode";
        $data['result'] = $this->Barcode_Model->get_barcode_id($id);
        $this->load->view("barcode/edit", $data);
    }

    public function remove($id) {
        if ($id) {

            $barcode = $this->Barcode_Model->get_barcode_id($id);

            $data = array(
                'barcode_status' => 0,
                'student_id' => "",
                'credit_date' => "0000-00-00"
            );
            $this->Barcode_Model->update($id, $data);

            if ($barcode) {
                $this->db->set('total_points', 'total_points-' . $barcode->student_point, FALSE);
                $this->db->set('total_balance', 'total_balance-' . $barcode->student_point, FALSE);
                $this->db->where('id', $barcode->student_id);
                $this->db->update('student');
            }

            $data2 = array(
                'type' => 2,
                'stud_id' => $barcode->student_id,
                'points' => $barcode->student_point,
                'balance' => $barcode->student_point,
                'category' => $barcode->category_id,
                'notes' => $barcode->notes_id,
                'barcode_id' => $id,
            );
            $this->db->insert('student_history', $data2);
            $this->session->set_flashdata('message', 'Successfully Removed');
            redirect('admin/barcode/', 'refresh');
        }
    }

    public function view() {
        if ($this->input->server("REQUEST_METHOD") == "POST") {
            $print = $this->input->post('print');
            $barcode_id = $this->input->post('barcode_id');
            $delete = $this->input->post('delete');
            $export = $this->input->post('export');
            if ($print) {
                $data['result'] = $this->Barcode_Model->get_barcode_ids($barcode_id);
                $data['title'] = $this->lang->line('print_barcode');
                $this->load->view("barcode/barcode_print", $data);
            }
            if ($delete) {
                $this->db->where_in('id', $barcode_id);
                $this->db->delete('barcode');
                $this->session->set_flashdata('message', 'Delete Successfully Updated');
                redirect("admin/barcode", "refresh");
            }
            if ($export) {
                $result = $this->Barcode_Model->get_barcode_ids($barcode_id);
                if ($result) {
                    $array = array();
                    foreach ($result as $key => $result_value) {
                        $array[] = array(
                            'image' => base_url('assets/images/points/' . $result_value->barcode),
                            'category' => $result_value->cname,
                            'notes' => $result_value->notes_name,
                            'credit_date' => $result_value->credit_date != "0000-00-00" ? $result_value->credit_date : "",
                            'point' => $result_value->student_point,
                            'name' => $result_value->name,
                            'status' => $result_value->barcode_status == 1 ? "USED" : "NOT USED",
                            'time' => $result_value->time
                        );
                    }
                }

                export_csv($array, "Points");
                die;
            }
        }
    }

    public function delete($id) {
        $this->Barcode_Model->delete($id);
        $this->session->set_flashdata('message', 'Successfully Deleted');
        redirect('points/barcode', 'refresh');
    }

    public function get_barcode_ajax($type = "") {

        $operator_id = $this->session->userdata('operator_id');
        $draw = intval($this->input->post("draw"));
        $start = intval($this->input->post("start"));
        $length = intval($this->input->post("length"));
        $order = $this->input->post("order");
        $search = $this->input->post("search");
        $search = $search['value'];
        $col = 0;
        $dir = "";
        if (!empty($order)) {
            foreach ($order as $o) {
                $col = $o['column'];
                $dir = $o['dir'];
            }
        }

        if ($dir != "asc" && $dir != "desc") {
            $dir = "desc";
        }

        /* $rows->barcode,
          $rows->name,
          $rows->profile_image,
          $rows->email,
          $rows->mobile,
          $rows->total_points,
          $rows->total_balance,

          $this->db->join('category c', 'c.id = barcode.category_id','left');
          $this->db->join('category n', 'n.id = barcode.notes_id','left');
         */
        $valid_columns = array(
            '',
            'scan_code',
            'c.category_name',
            'n.category_name',
            'credit_date',
            'student_point',
            's.name',
            'barcode_status',
            'barcode.time',
            ''
        );
        if (!isset($valid_columns[$col])) {
            $order = null;
        } else {
            $order = $valid_columns[$col];
        }
        if ($order != null) {
            $this->db->order_by($order, $dir);
        }

        if (!empty($search)) {
            $x = 0;
            foreach ($valid_columns as $sterm) {
                if ($sterm) {
                    if ($x == 0) {
                        $this->db->like($sterm, $search);
                    } else {
                        $this->db->or_like($sterm, $search);
                    }
                    $x++;
                }
            }
        }

        //print_r($this->input->post("data"));die;
        $form_data = $this->input->post("datajson");
        if ($form_data) {
            $json_data = json_decode($form_data);
            foreach ($json_data as $key => $value) {
                //pr($value);
                if ($value->name && $value->value) {
                    //echo $value->name;
                    if ($value->name == "date_from_to") {
                        $from = explode(" - ", $value->value)[0];
                        $to = explode(" - ", $value->value)[1];
                        $to = date('Y-m-d', strtotime($to . ' +1 day'));
                        $this->db->where("barcode.time BETWEEN '$from' AND '$to'");
                    } elseif ($value->name == "barcode_status") {
                        if ($value->value == 2)
                            $status = 0;
                        else
                            $status = 1;
                        $this->db->where($value->name, $status);
                    }
                    else {
                        $col_name = str_replace("[", "", $value->name);
                        $col_name = str_replace("]", "", $col_name);
                        $this->db->where_in($col_name, $value->value);
                    }
                }
            }
        }

        if ($type >= 0 && $type != "")
            $this->db->where('barcode_status', $type);
        $this->db->select('barcode.*,c.category_name as cname,n.category_name as notes_name,s.username as name');
        $this->db->join('pts_category c', 'c.id = barcode.category_id', 'left');
        $this->db->join('pts_category n', 'n.id = barcode.notes_id', 'left');
        $this->db->join('bills_user s', 's.id = barcode.student_id', 'left');
        $this->db->limit($length, $start);
        $query = $this->db->get('pts_barcode barcode');
        $data = array();
        foreach ($query->result() as $result) {
            $history = "";
            $confrim_opt = "return  confirm('are you sure?');";

            if ($result->student_id > 0) {
                if (get_ap('points_ac_remove', $operator_id) == 1) {
                    $history .= '<a href="' . base_url() . 'points/barcode/remove/' . $result->id . '" class="btn btn-success  btn-sm"  onclick="' . $confrim_opt . '" ><i class="fa fa-close"></i></a>';
                }
            }
            if (get_ap('points_ac_delete', $operator_id) == 1) {
                $history .= '<a href="' . base_url() . 'points/barcode/delete/' . $result->id . '" class="btn btn-danger  btn-sm" onclick="' . $confrim_opt . '"><i class="fa fa-trash"></i></a>';
            }

            $stauts = $result->barcode_status == 1 ? "<span class='btn btn-success  btn-sm'>" . $this->lang->line('used') . "</span>" : "<span class='btn btn-danger  btn-sm'>" . $this->lang->line('not_used') . "</span>";

            $data[] = array(
                '<input type="checkbox" name="barcode_id[]" class="barcode_id" value="' . $result->id . '">',
                '<img src="' . base_url("uploads/points/" . $result->barcode) . '" width="80" alt="">',
                $result->cname,
                $result->notes_name,
                $result->credit_date == "0000-00-00" ? "-" : $result->credit_date,
                $result->student_point,
                $result->name,
                $stauts,
                $result->time,
                $history
            );
        }
        $total_employees = $this->totalEmployees($type);
        $output = array(
            "draw" => $draw,
            "recordsTotal" => $total_employees,
            "recordsFiltered" => $total_employees,
            "data" => $data
        );
        echo json_encode($output);
        exit();
    }

    public function totalEmployees($type) {
        if ($type >= 0 && $type != "")
            $this->db->where('barcode_status', $type);
        $query = $this->db->select("COUNT(*) as num")->get("pts_barcode");
        $result = $query->row();
        if (isset($result))
            return $result->num;
        return 0;
    }

}
