<?php

namespace App\Http\Services\Backend\DataManagement;

use App\Http\Services\ConstDef\GeneralConst;
use App\Models\Web\Session;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Support\Facades\DB;
use App\Models\Web\Round;
use App\Models\Web\Good;

class SessionManagementService
{
    // 相關私有 model 調用器宣告
    private $sessionManagementDb;
    private $roundManagementDb;
    private $goodManagementDb;
    
    public function __construct()
    {
        // 建構 model 調用器
        $this->sessionManagementDb = new Session();
        $this->roundManagementDb = new Round();
        $this->goodManagementDb = new Good();
    }
    
    public function getRounds()
    {
        $rounds = $this->roundManagementDb->select([
            'id',
            'roundName',
        ])
            ->get()
            ->toArray();
        
        return $rounds;
    }
    
    public function getGoods()
    {
        $goods = $this->goodManagementDb->select([
            'id',
            'lp',
        ])
            ->get()
            ->toArray();
        
        return $goods;
    }
    
    public function getSessions(
        &$cnt = 0,
        $orderColumn,
        $orderDir,
        $start,
        $length,
        $searchValue,
        $lineId,
        $userName,
        $round,
        $good,
        $createDateStart,
        $createDateFinal
    )
    {
        $sessions = $this->sessionManagementDb
            ->leftJoin('rounds', 'sessions.rid', '=', 'rounds.id')
            ->leftJoin('gameGpRatio', 'sessions.gid', '=', 'gameGpRatio.id')
            ->leftJoin('goods', 'sessions.cid', '=', 'goods.id')
            ->select([
                'sessions.id',
                'sessions.lineId',
                'sessions.userName',
                'rounds.roundName',
                'goods.lp',
                'sessions.eventDate',
                'sessions.currentGameGp',
                'sessions.currentCheckinGp',
                'sessions.currentGp',
                'sessions.cdate',
            ]);
        // 過濾搜尋條件
        if ($lineId != '') $sessions = $sessions->where('sessions.lineId', 'like', '%' . $lineId . '%');
        if ($userName != '') $sessions = $sessions->where('sessions.userName', 'like', '%' . $userName . '%');
        if ($round != '') $sessions = $sessions->where('rounds.id', '=', $round);
        if ($good != '') $sessions = $sessions->where('goods.id', '=', $good);
        $sessions = $sessions->where('sessions.cdate', '>=', $createDateStart . ' 00:00:00');
        $sessions = $sessions->where('sessions.cdate', '<=', $createDateFinal . ' 23:59:59');
        // 取總筆數
        $cnt = $sessions->count();
        // 排序
        $sessions = $sessions
            ->orderByRaw((int)$orderColumn . ' ' . 'ASC');
        // 彙整
        // 分頁
        $sessions = $sessions
            ->skip($start)->take($length);
        // 實際取資料
        $sessions = $sessions
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $sessions;
    }
    
    public function getExports($param)
    {
        $sessions = $this->sessionManagementDb
            ->leftJoin('rounds', 'sessions.rid', '=', 'rounds.id')
            ->leftJoin('goods', 'sessions.gid', '=', 'goods.id')
            ->select([
                'sessions.id',
                'sessions.lineId',
                'sessions.userName',
                'rounds.roundName',
                'goods.lp',
                'sessions.eventDate',
                'sessions.currentGameGp',
                'sessions.currentCheckinGp',
                'sessions.currentGp',
                'sessions.cdate',
            ]);
        // 過濾搜尋條件
        if ($param["lineId"] != '') $sessions = $sessions->where('sessions.lineId', 'like', '%' . $param["lineId"] . '%');
        if ($param["userName"] != '') $sessions = $sessions->where('sessions.userName', 'like', '%' . $param["userName"] . '%');
        if ($param["round"] != '') $sessions = $sessions->where('rounds.id', '=', $param["round"]);
        if ($param["good"] != '') $sessions = $sessions->where('goods.id', '=', $param["good"]);
        $sessions = $sessions->where('sessions.cdate', '>=', $param["createDateStart"] . ' 00:00:00');
        $sessions = $sessions->where('sessions.cdate', '<=', $param["createDateFinal"] . ' 23:59:59');
        // 實際取資料
        $sessions = $sessions
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $sessions;
    }
    
    public function downloadExcel($titles = [], $datas = [], $fileName = 'simple')
    {
        $spreadsheet = new Spreadsheet();
        ini_set('memory_limit', '1024M');
        ini_set("max_execution_time", "600");
        $spreadsheet->getActiveSheet()
            ->fromArray(
                $titles, // The data to set
                null, // Array values with this value will not be set
                'A1' // Top left coordinate of the worksheet range where we want to set these values (default is A1)
            );
        
        $spreadsheet->getActiveSheet()
            ->fromArray(
                $datas, // The data to set
                null, // Array values with this value will not be set
                'A2' // Top left coordinate of the worksheet range where we want to set these values (default is A1)
            );
        
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }
    
}