<?php

namespace App\Http\Controllers\Backend\DataManagement;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Services\CheckParamService;
use App\Http\Controllers\Controller;
use App\Http\Services\Backend\DataManagement\SignupManagementService;
use Log;
use Illuminate\Support\Facades\Session;
use Spatie\SimpleExcel\SimpleExcelWriter;

class SignupManagementController extends Controller
{
    
    // 相關私有服務層調用器宣告
    private $checkParamSv;
    private $signupManagementSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->checkParamSv=new CheckParamService();
        $this->signupManagementSv = new SignupManagementService();
    }
    public function index()
    {
        // 取得參數
        $param = $_GET;
        // 渲染
        return view('admin.DataManagement.SignupManagement');

    }
    public function grid()
    {
        // 取得參數
        $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"];
        //客製化搜尋欄位
        $keyword = $param["columns"][1]["search"]["value"];
        $trackNo = $param["columns"][2]["search"]["value"];
        $createDateStart = $param["columns"][3]["search"]["value"];
        $createDateFinal = $param["columns"][4]["search"]["value"];
        
        // \Log::info('createDateStart: '.$createDateStart);
        // \Log::info('createDateFinal: '.$createDateFinal);
        // 驗證
        if ($keyword != filter_var($keyword, FILTER_SANITIZE_SPECIAL_CHARS)) $keyword = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($keyword, 0, 50)) $keyword = "___CANNOT_FIND_STRING___";
        if ($trackNo != filter_var($trackNo, FILTER_SANITIZE_SPECIAL_CHARS)) $trackNo = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($trackNo, 0, 50)) $trackNo = "___CANNOT_FIND_STRING___";
        if ($createDateStart != filter_var($createDateStart, FILTER_SANITIZE_SPECIAL_CHARS)) $createDateStart = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($createDateStart, 0, 50)) $createDateStart = "___CANNOT_FIND_STRING___";
        if ($createDateFinal != filter_var($createDateFinal, FILTER_SANITIZE_SPECIAL_CHARS)) $createDateFinal = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($createDateFinal, 0, 50)) $createDateFinal = "___CANNOT_FIND_STRING___";
        
        if ($createDateStart&&$createDateFinal&&$createDateStart>$createDateFinal) {
            Session::flash('msg', '請填入正確起訖日!');
            return redirect()->back();
        }
        if (!$createDateStart) {
            $createDateStart = "2022-09-10 00:00:00";
        } else {
            $createDateStart = $createDateStart." 00:00:00";
        }
        
        if (!$createDateFinal) {
            $createDateFinal = date('Y-m-d H:i:s');
        } else {
            $createDateFinal = $createDateFinal." 23:59:59";
        }
        
        
        //資料庫
        $recordsTotal = 0;
        if ($keyword) {
            $result=$this->signupManagementSv->getList($recordsTotal, $orderColumn, $orderDir, $start, $length, $searchValue, $this->safeEncrypt(($keyword), 'arm'), $trackNo, $createDateStart, $createDateFinal);
        } else {
            $result=$this->signupManagementSv->getList($recordsTotal, $orderColumn, $orderDir, $start, $length, $searchValue, '', $trackNo, $createDateStart, $createDateFinal);
        }
        
        // 外部短網址系統串接
        $orlCodeIds = array();

        // 整理返回資料
        $data = array();
        $registeredSession = '';
        $lunchOptions = '';
        for ($i = 0; $i < count($result); $i++) {
            
            $data[] = array(
                //一般資料
                $result[$i]["id"],
                htmlspecialchars($this->safeDecrypt($result[$i]["firstName"], 'arm')),
                htmlspecialchars($this->safeDecrypt($result[$i]["lastName"], 'arm')),
                htmlspecialchars($this->safeDecrypt($result[$i]["companyName"], 'arm')),
                htmlspecialchars($result[$i]["country"]),
                htmlspecialchars($result[$i]["trackNo"]),
                htmlspecialchars($result[$i]["registeredSession"]),
                htmlspecialchars($result[$i]["lunchOptions"]),
                $result[$i]["createDate"],
            );
        }
        $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 (!$request->keyword) {
            Session::flash('msg', '請填入關鍵字!');
            return redirect()->back();
        }
        */
        \Log::info(print_r($request->all(),true));
        $keyword = $request->keyword;
        $trackNo = $request->trackNo;
        $createDateStart = $request->createDateStart;
        $createDateFinal = $request->createDateFinal;

        if (!$createDateStart) {
            $createDateStart = "2022-09-10 00:00:00";
        } else {
            $createDateStart = $createDateStart." 00:00:00";
        }
        
        if (!$createDateFinal) {
            $createDateFinal = date('Y-m-d H:i:s');
        } else {
            $createDateFinal = $createDateFinal." 23:59:59";
        }
        
        if ($keyword) {
            $datas = $this->signupManagementSv->getExportList($this->safeEncrypt(($keyword), 'arm'), $trackNo, $createDateStart, $createDateFinal);
        } else {
            $datas = $this->signupManagementSv->getExportList('', $trackNo, $createDateStart, $createDateFinal);
        }
        
        $rows = [];
        foreach ($datas as $data) {
            
            if ($data['backupEmail']) {
                $backupEmail = $this->safeDecrypt($data['backupEmail'], 'arm');
            } else {
                $backupEmail = '';
            }

            $rows[] = [
                '序號' => $data['id'],
                'firstName' => $this->safeDecrypt($data['firstName'], 'arm'),
                'lastName' => $this->safeDecrypt($data['lastName'], 'arm'),
                'companyName' => $this->safeDecrypt($data['companyName'], 'arm'),
                'companyEmail' => $this->safeDecrypt($data['companyEmail'], 'arm'),
                'backupEmail' => $backupEmail,
                'phoneNumber' => $this->safeDecrypt($data['phoneNumber'], 'arm'),
                'country' => $data['country'],
                'trackNo' => $data['trackNo'],
                'registeredSession(TW only)' => $data['registeredSession'],
                'lunchOptions(TW only)' => $data['lunchOptions'],
                'typeOfIndustry' => $data['typeOfIndustry'],
                'typeOfJob' => $data['typeOfJob'],
                'jobTitle' => $data['jobTitle'],
                'trackOfInterest' => $data['trackOfInterest'],
                'areaOfInterest' => $data['areaOfInterest'],
                'howToKnowAboutTheEvent' => $data['howToKnowAboutTheEvent'],
                'consentAcceptEmail' => $data['consentAcceptEmail'],
                'consentPrivacyPolicy' => $data['consentPrivacyPolicy'],
                '報名時間' => $data['createDate'],
            ];
        }

        SimpleExcelWriter::streamDownload('報名資料'.date('YmdHis').'.xlsx')
            ->addRows($rows)
            ->toBrowser();
    }

    /**
     * 參數加解密模組: 加密部分，建議使用環境變數中的 secret key 作加解密種子
     */
    public function safeEncrypt(string $message, string $skey): string
    {
        
        $strArr = str_split(base64_encode($message));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
        $key < $strCount && $strArr[$key].=$value;
        return str_replace(array('=', ' ', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }
    
    /**
     * 參數加解密模組: 解密部分，建議使用環境變數中的 secret key 作加解密種子
     */
    public function safeDecrypt(string $encrypted, string $skey): string
    {
        $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', ' ', '/'), $encrypted), 2);
        $strCount = count($strArr);

        foreach (str_split($skey) as $key => $value) {
            $key <= $strCount && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        }
            
        return base64_decode(join('', $strArr));
    }
    
}