<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 25/12/2015
 * Time: 2:22 CH
 */
if (!defined('BASEPATH')) exit('No direct script access allowed');
//require_once APPPATH."/third_party/PHPExcel.php";
//include FCPATH . "/application/third_party/PHPExcel/IOFactory.php";
include FCPATH . "/application/third_party/PHPExcel.php";

class CmsRanking extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Ho_Chi_Minh");
        //
        $this->load->model('track_model');
        $this->load->model('user_model');
        $this->load->model('report_views_daily_model');
        $this->load->model('report_views_weekly_model');
        $this->load->model('report_views_monthly_model');
    }

    public function listByDaily()
    {
        $this->_data['functionName'] = 'BXH theo ngày';
        $this->_data['action'] = 'listByDaily';
        $this->_data['titlePage'] = 'BXH theo ngày';
        $this->_data['loadPage'] = 'backend/cms_ranking/list_by_daily_view';
        $this->load->view('backend/admin_template_view', $this->_data);
    }

    public function listByDailyAjax()
    {
        $data = array();
        $fByName = $this->input->post('fByName');
        $pageId = $this->input->post('pageId');
        //
        $pageId = ($pageId == 0) ? 1 : $pageId;
        //
        $limit = 100;
        $offset = ($pageId - 1) * $limit;
        $data['offset'] = ($pageId - 1) * $limit;
        $totalRecord = $this->report_views_daily_model->cmsCountAll($fByName);
        $data['pagination'] = MyHelper::genPaginationLink($totalRecord, $limit, $pageId);
        $data['listData'] = $this->report_views_daily_model->cmsGetPagination($limit, $offset, $fByName);
        //
        $this->load->view('backend/ajax/cms_ranking/list_by_daily_view', $data);
    }

    /**
     * BXH theo tuần ---------------------------------------------------------------------------------------------------
     */
    public function listByWeekly()
    {
        $this->_data['functionName'] = 'BXH theo tuần';
        $this->_data['action'] = 'listByDaily';
        $this->_data['titlePage'] = 'BXH theo tuần';
        $this->_data['loadPage'] = 'backend/cms_ranking/list_by_weekly_view';
        $this->load->view('backend/admin_template_view', $this->_data);
    }

    public function listByWeeklyAjax()
    {
        $data = array();
        $fByName = $this->input->post('fByName');
        $pageId = $this->input->post('pageId');
        //
        $pageId = ($pageId == 0) ? 1 : $pageId;
        //
        $limit = 100;
        $offset = ($pageId - 1) * $limit;
        $data['offset'] = ($pageId - 1) * $limit;
        $totalRecord = $this->report_views_weekly_model->cmsCountAll($fByName);
        $data['pagination'] = MyHelper::genPaginationLink($totalRecord, $limit, $pageId);
        $data['listData'] = $this->report_views_weekly_model->cmsGetPagination($limit, $offset, $fByName);
        //
        
        // print_r($fByName);
        $this->load->view('backend/ajax/cms_ranking/list_by_weekly_view', $data);
    }

    /**
     * BXH theo tháng --------------------------------------------------------------------------------------------------
     */
    public function listByMonthly()
    {
        $this->_data['functionName'] = 'BXH theo tháng';
        $this->_data['action'] = 'listByDaily';
        $this->_data['titlePage'] = 'BXH theo tháng';
        $this->_data['loadPage'] = 'backend/cms_ranking/list_by_monthly_view';
        $this->load->view('backend/admin_template_view', $this->_data);
    }

    public function listByMonthlyAjax()
    {
        $data = array();
        $fByName = $this->input->post('fByName');
        $pageId = $this->input->post('pageId');
        //
        $pageId = ($pageId == 0) ? 1 : $pageId;
        //
        $limit = 100;
        $offset = ($pageId - 1) * $limit;
        $data['offset'] = ($pageId - 1) * $limit;
        $totalRecord = $this->report_views_monthly_model->cmsCountAll($fByName);
        $data['pagination'] = MyHelper::genPaginationLink($totalRecord, $limit, $pageId);
        $data['listData'] = $this->report_views_monthly_model->cmsGetPagination($limit, $offset, $fByName);
        //
        $this->load->view('backend/ajax/cms_ranking/list_by_monthly_view', $data);
    }

    /**
     * Export BXH ngày, tuần, tháng ra excel ---------------------------------------------------------------------------
     * @param $type
     * @param $time
     */
    public function exportReport($type, $time)
    {
        if ($type && $time) {
            $arrayTime = explode('-', $time);

            $week = date('W');
            $month = date('n');
            $year = date('Y');

            if ($type == 'week') {
                $week = trim($arrayTime[0]);
                $year = trim($arrayTime[1]);
                $filename = 'Weekly-tuan' . (($week < 10) ? '0'.$time : $time);
                $reports = $this->track_model->getReportWeekly($week, $year);
            } elseif ($type == 'month') {
                $month = trim($arrayTime[0]);
                $year = trim($arrayTime[1]);
                $filename = 'Monthly-' . (($month < 10) ? '0'.$time : $time);
                $reports = $this->track_model->getReportMonthly($month, $year);
            }

            $count_views = [];
            foreach ($reports as $key => $result) {
                $list_user = $this->track_model->getUserByTrack($result['track_id']);
                $casi[$key] = [];
                if ($list_user && count($list_user) > 0) {
                    foreach ($list_user as $k => $users){
                        $singer = $this->user_model->getUser($users['user_id']);
                        if ($singer) {
                            $casi[$key][] = $singer[0]['full_name'];
                        }else {
                            $casi[$key][] = $list_user[$k]['name'];
                        }
                    }
                }

                $list_artists = $this->track_model->getArtistsByTrack($result['track_id']);
                $nhacsi[$key] = [];
                if ($list_artists ) {
                    foreach ($list_artists as  $k_art => $art){
                        $artist = $this->user_model->getUser($art['user_id']);
                        if ($artist) {
                            $nhacsi[$key][] = $artist[0]['full_name'];
                        }else {
                            $nhacsi[$key][] = $list_artists[$k_art]['name'];
                        }
                    }
                }
                $track_detail =  $this->track_model->getTrackById($result['track_id']);
                $track_detail = $track_detail[0];
                $count_views[] = array(
                    'A' => $result['order'],
                    //'B' => ($track_detail['title'] != '') ? $track_detail['title'] . ' (' . $track_detail['id'] . ')' : '',
                    'B' => ($track_detail['title'] != '') ? $track_detail['title'] : '',
                    'C' => ($casi[$key] && count($casi[$key]) > 0 ) ? implode(", ", $casi[$key]) : '',
                    'D' => ($nhacsi[$key] && count($nhacsi[$key]) > 0 ) ? implode(", ", $nhacsi[$key]) : '',
                    'E' => number_format($result['views_zing']),
                    'F' => number_format($result['views_nct']),
                    'G' => number_format($result['views_keeng']),
                    'H' => 0,
                    'I' => number_format($result['point_zing']),
                    'J' => number_format($result['point_nct']),
                    'K' => number_format($result['point_keeng']),
                    'L' => 0,
                    'M' => number_format($result['total_point'])
                );
            }

            $objPHPExcel = new PHPExcel;
            // set default font
            $objPHPExcel->getDefaultStyle()->getFont()->setName('Tahoma');
            // set default font size
            $objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
            // writer already created the first sheet for us, let's get it
            $objSheet = $objPHPExcel->getActiveSheet();
            // rename the sheet
            $objSheet->setTitle($filename);

            $objSheet->getCell('A1')->setValue("Rank");
            $objSheet->getCell('B1')->setValue("Song Title");
            $objSheet->getCell('C1')->setValue("Artist");
            $objSheet->getCell('D1')->setValue("Composer");
            $objSheet->getCell('E1')->setValue("Zing Stream");
            $objSheet->getCell('F1')->setValue("NCT Stream");
            $objSheet->getCell('G1')->setValue("Keeng Stream");
            $objSheet->getCell('H1')->setValue("Nhac.vn Stream");
            $objSheet->getCell('I1')->setValue("Zing Point");
            $objSheet->getCell('J1')->setValue("NCT Point");
            $objSheet->getCell('K1')->setValue("Keeng Point");
            $objSheet->getCell('L1')->setValue("Nhac.vn Point");
            $objSheet->getCell('M1')->setValue("TOTAL POINT");
            $border_style = array(
                'borders' =>array(
                    'allborders' => array(
                        'style'      => PHPExcel_Style_Border::BORDER_THIN,
                        'color'      => array('rgb' => '000000')
                    )
                )
            );
            $style_header = array(
                'font' => array(
                    'bold' => true,
                ),
                'alignment' =>array(
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    'vertical' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
                'fill' =>array(
                    'type' => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => '8DB4E2'),
                ),
            );

            $objSheet->getStyle('A1:M1')->applyFromArray($style_header);
            $objSheet->getStyle("A1:M1")->applyFromArray($border_style);

            $style_top10 = array(
                'font' => array(
                    'bold' => true,
                ),
            );
            $objSheet->getStyle('A2:D11')->applyFromArray($style_top10);

            // In du lieu vao bang
            foreach ($count_views as $hang => $hd) {
                for ($i = 65; $i <= 77; $i++) {
                    if ($i == 66 || $i == 67 || $i == 68) {
                        $objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                    }else {
                        $objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    }
                    // $hd[chr($i)] = (!empty($hd[chr($i)])) ? $hd[chr($i)] : '';
                    $objSheet->getCell(chr($i).($hang+2))->setValue($hd[chr($i)]);
                    $objSheet->getStyle(chr($i).($hang+2))->applyFromArray($border_style);
                    $objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setWrapText(true);
                    $objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

                    // Set size column
                    // $objSheet->getColumnDimension(chr($i))->setAutoSize(false);
                    if ($i == 65) {
                        $objSheet->getColumnDimension(chr($i))->setWidth("8");
                    }elseif($i == 66 || $i == 67 || $i == 68) {
                        $objSheet->getColumnDimension(chr($i))->setWidth("26");
                    }else {
                        $objSheet->getColumnDimension(chr($i))->setWidth("12");
                    }
                }
            }

            $objSheet->getStyle('A1:M1')->getAlignment()->setWrapText(true);

            header('Content-type: application/vnd.ms-excel');
            header('Content-Disposition: attachment; filename="' . $filename . '.xlsx"');
            PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007')->save('php://output');;
            die();

        } else {
            redirect(base_url('backend/home/index'));
        }
    }

}