<?php

namespace App\Http\Controllers\Backend\DataManagement;

use Illuminate\Http\Request;
use App\Http\Services\Backend\DataManagement\TSessionManagementService;
use App\Http\Controllers\Controller;
use App\Http\Services\ConstDef\GeneralConst;
use App\Http\Services\CheckParamService;

class TSessionManagementController extends Controller
{
    // 相關私有服務層調用器宣告
    private $tsessionManagementSv;
    private $checkParamSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->tsessionManagementSv = new TSessionManagementService();
        $this->checkParamSv = new CheckParamService();
        // 時區調整
        date_default_timezone_set("Asia/Taipei");
    }
    
    public function index(Request $request)
    {
        // 渲染
        return view('admin.DataManagement.TSessionManagement', [
            'tround' => $this->tsessionManagementSv->getTRounds(),
        ]);
    }
    
    public function grid(Request $request)
    {
        // 取得參數
        $param = $_GET;
        if ($param == null) exit();
        $draw = $param["draw"]; //客戶端傳來的查詢次數，無條件回傳用以核對
        $orderColumn = $param["order"][0]["column"] + 1; //前端從 0 開始送，但 mysql 從 1 開始算
        $orderDir = $param["order"][0]["dir"];
        $start = $param["start"];   // 頁碼
        $length = $param["length"]; // 一頁多大
        $searchValue = $param["search"]["value"];
        //客製化搜尋欄位
        $lineId = $param["columns"][1]["search"]["value"];
        $userName = $param["columns"][2]["search"]["value"];
        $tround = $param["columns"][3]["search"]["value"];
        $createDate = explode("\n", $param["columns"][4]["search"]["value"]);
        $createDateStart = $createDate[0] ?? null;
        $createDateFinal = $createDate[1] ?? null;
        // 驗證
        if ($lineId != filter_var($lineId, FILTER_SANITIZE_SPECIAL_CHARS)) $lineId = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($lineId, 0, 50)) $lineId = "___CANNOT_FIND_STRING___";
        if ($userName != filter_var($userName, FILTER_SANITIZE_SPECIAL_CHARS)) $userName = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($userName, 0, 100)) $userName = "___CANNOT_FIND_STRING___";
        if ($createDateStart == "") $createDateStart = "1900-01-01";
        if ($createDateFinal == "") $createDateFinal = "2050-12-31";
        if (!$this->checkParamSv->validateDate($createDateStart, 'Y-m-d')) $createDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($createDateFinal, 'Y-m-d')) $createDateFinal = "2050-12-31";
        //資料庫
        $recordsTotal = 0;
        $result = $this->tsessionManagementSv->getTSessions(
            $recordsTotal,
            $orderColumn,
            $orderDir,
            $start,
            $length,
            $searchValue,
            $lineId,
            $userName,
            $tround,
            $createDateStart,
            $createDateFinal
        );
        // 整理返回資料
        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $data[] = array(
                //一般資料
                $result[ $i ]["id"],
                $result[ $i ]["lineId"],
                $result[ $i ]["userName"],
                $result[ $i ]["roundName"],
                $result[ $i ]["gid"],
                $result[ $i ]["eventDate"],
                $result[ $i ]["currentGameGp"],
                $result[ $i ]["currentCheckinGp"],
                $result[ $i ]["currentGp"],
                $result[ $i ]["cdate"],
            );
        }
        $json = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsTotal, //其實還是填入所有筆數，本次筆數可從陣列取得
            "data"            => $data,
        );
        
        // 返回
        return json_decode(json_encode($json, JSON_NUMERIC_CHECK), true);
    }
    
    public function export(Request $request)
    {
        // 取得參數
        $param = $_POST;
        if ($param == null) exit();
        // 驗證
        if ($param['lineId'] != filter_var($param['lineId'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['lineId'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['lineId'], 0, 50)) $param['lineId'] = "___CANNOT_FIND_STRING___";
        if ($param['userName'] != filter_var($param['userName'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['userName'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['userName'], 0, 100)) $param['userName'] = "___CANNOT_FIND_STRING___";
        if ($param['createDateStart'] == "") $param['createDateStart'] = "1900-01-01";
        if ($param['createDateFinal'] == "") $param['createDateFinal'] = "2050-12-31";
        if (!$this->checkParamSv->validateDate($param['createDateStart'], 'Y-m-d')) $param['createDateStart'] = "1900-01-01";
        if (!$this->checkParamSv->validateDate($param['createDateFinal'], 'Y-m-d')) $param['createDateFinal'] = "2050-12-31";
        // 製作
        $title = [
            'ID',
            '玩家 LINE ID',
            '玩家名稱',
            '回合',
            '格子或簽到',
            '日期',
            '遊戲吉點',
            '簽到吉點',
            '本次吉點異動',
            '時間戳',
        ];
        $tsessions = $this->tsessionManagementSv->getExports($param);
        $this->tsessionManagementSv->downloadExcel($title, $tsessions, date("YmdHis") . '-TSESSION-REPORT');
    }
}