<?php

namespace App\Http\Controllers\Backend\DataManagement;

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

class ReceiptManagementController extends Controller
{
    // 相關私有服務層調用器宣告
    private $receiptManagementSv;
    private $checkParamSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->receiptManagementSv = new ReceiptManagementService();
        $this->checkParamSv = new CheckParamService();
        // 時區調整
        date_default_timezone_set("Asia/Taipei");
    }
    
    public function index(Request $request)
    {
        // 渲染
        return view('admin.DataManagement.ReceiptManagement', [
            'activity' => $this->receiptManagementSv->getActivitys(),
            'rStatus'  => GeneralConst::$rStatusMap,
            'canGet'   => GeneralConst::$canGetMap,
        ]);
    }
    
    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"];
        //客製化搜尋欄位
        $tranDate = explode("\n", $param["columns"][1]["search"]["value"]);
        $tranDateStart = $tranDate[0] ?? null;
        $tranDateFinal = $tranDate[1] ?? null;
        $tranBank = $param["columns"][2]["search"]["value"];
        $tranAccount = $param["columns"][3]["search"]["value"];
        $tranOrderNo = $param["columns"][4]["search"]["value"];
        $lineId = $param["columns"][5]["search"]["value"];
        $lineName = $param["columns"][6]["search"]["value"];
        $activity = $param["columns"][7]["search"]["value"];
        $rStatus = $param["columns"][8]["search"]["value"];
        $canGet = $param["columns"][9]["search"]["value"];
        // 驗證
        if ($tranDateStart == "") $tranDateStart = "1900-01-01";
        if ($tranDateFinal == "") $tranDateFinal = "2050-12-31";
        if (!$this->checkParamSv->validateDate($tranDateStart, 'Y-m-d')) $tranDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($tranDateFinal, 'Y-m-d')) $tranDateFinal = "2050-12-31";
        if ($tranBank != filter_var($tranBank, FILTER_SANITIZE_SPECIAL_CHARS)) $tranBank = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($tranBank, 0, 10)) $tranBank = "___CANNOT_FIND_STRING___";
        if ($tranAccount != filter_var($tranAccount, FILTER_SANITIZE_SPECIAL_CHARS)) $tranAccount = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($tranAccount, 0, 30)) $tranAccount = "___CANNOT_FIND_STRING___";
        if ($tranOrderNo != filter_var($tranOrderNo, FILTER_SANITIZE_SPECIAL_CHARS)) $tranOrderNo = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($tranOrderNo, 0, 30)) $tranOrderNo = "___CANNOT_FIND_STRING___";
        if ($lineId != filter_var($lineId, FILTER_SANITIZE_SPECIAL_CHARS)) $lineId = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($lineId, 0, 64)) $lineId = "___CANNOT_FIND_STRING___";
        if ($lineName != filter_var($lineName, FILTER_SANITIZE_SPECIAL_CHARS)) $lineName = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($lineName, 0, 64)) $lineName = "___CANNOT_FIND_STRING___";
        //資料庫
        $recordsTotal = 0;
        $result = $this->receiptManagementSv->getReceipts(
            $recordsTotal,
            $orderColumn,
            $orderDir,
            $start,
            $length,
            $searchValue,
            $tranDateStart,
            $tranDateFinal,
            $tranBank,
            $tranAccount,
            $tranOrderNo,
            $lineId,
            $lineName,
            $activity,
            $rStatus,
            $canGet
        );
        // 整理返回資料
        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $data[] = array(
                //一般資料
                $result[ $i ]["id"],
                $result[ $i ]["tranDate"],
                $result[ $i ]["tranBank"],
                $result[ $i ]["tranAccount"],
                $result[ $i ]["tranOrderNo"],
                $result[ $i ]["lineId"],
                $result[ $i ]["lineName"],
                $result[ $i ]["activityName"],
                $result[ $i ]["rStatus"],
                $result[ $i ]["canGet"],
                $result[ $i ]["cdate"],
                $result[ $i ]["mdate"],
                $result[ $i ]["oid"],
            );
        }
        $json = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsTotal, //其實還是填入所有筆數，本次筆數可從陣列取得
            "data"            => $data,
        );
        
        // 返回
        return json_decode(json_encode($json), true);
    }
    
    public function export(Request $request)
    {
        // 取得參數
        $param = $_POST;
        if ($param == null) exit();
        // 驗證
        if ($param['tranDateStart'] == "") $param['tranDateStart'] = "1900-01-01";
        if ($param['tranDateFinal'] == "") $param['tranDateFinal'] = "2050-12-31";
        if (!$this->checkParamSv->validateDate($param['tranDateStart'], 'Y-m-d')) $param['tranDateStart'] = "1900-01-01";
        if (!$this->checkParamSv->validateDate($param['tranDateFinal'], 'Y-m-d')) $param['tranDateFinal'] = "2050-12-31";
        if ($param['tranBank'] != filter_var($param['tranBank'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['tranBank'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['tranBank'], 0, 10)) $param['tranBank'] = "___CANNOT_FIND_STRING___";
        if ($param['tranAccount'] != filter_var($param['tranAccount'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['tranAccount'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['tranAccount'], 0, 30)) $param['tranAccount'] = "___CANNOT_FIND_STRING___";
        if ($param['tranOrderNo'] != filter_var($param['tranOrderNo'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['tranOrderNo'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['tranOrderNo'], 0, 30)) $param['tranOrderNo'] = "___CANNOT_FIND_STRING___";
        if ($param['lineId'] != filter_var($param['lineId'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['lineId'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['lineId'], 0, 64)) $param['lineId'] = "___CANNOT_FIND_STRING___";
        if ($param['lineName'] != filter_var($param['lineName'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['lineName'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['lineName'], 0, 64)) $param['lineName'] = "___CANNOT_FIND_STRING___";
        // 製作
        $title = [
            'ID',
            '交易日期',
            '交易行號',
            '交易帳號',
            '訂單編號',
            '玩家 LINE ID',
            '玩家 LINE 姓名',
            '活動名稱',
            '狀態',
            '是否發放',
            '建立時間',
            '修改時間',
            '修改人',
        ];
        $receipts = $this->receiptManagementSv->getExports($param);
        $this->receiptManagementSv->downloadExcel($title, $receipts, date("YmdHis") . '-RECEIPT-REPORT');
    }
    
    public function redeemDone(Request $request)
    {
        // 取得參數
        $chk = $request->input('chk', []);
        // 執行
        if (count($chk) > 0) $this->receiptManagementSv->redeemDone($chk, $request->user()->id);
        
        // 返回
        return response()->json(["succ" => true, "err" => '']);
    }
    
    public function redeemFail(Request $request)
    {
        // 取得參數
        $chk = $request->input('chk', []);
        // 執行
        if (count($chk) > 0) $this->receiptManagementSv->redeemFail($chk, $request->user()->id);
        
        // 返回
        return response()->json(["succ" => true, "err" => '']);
    }
    
}