<?php

namespace App\Http\Controllers\Backend\DataManagement;

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

class SettingManagementController extends Controller
{
    
    private $settingManagementSv;
    private $checkParamSv;
    
    public function __construct()
    {
        $this->settingManagementSv = new SettingManagementService();
        $this->checkParamSv = new CheckParamService();
        date_default_timezone_set("Asia/Taipei");
    }
    
    public function index()
    {
        return view('admin.DataManagement.SettingManagement', [
            'active' => GeneralConst::$activeMap,
        ]);
    }
    
    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"];
        //客製化搜尋欄位
        $name = $param["columns"][1]["search"]["value"];
        $cDate = explode("\n", $param["columns"][2]["search"]["value"]);
        $cDateStart = $cDate[0] ?? null;
        $cDateFinal = $cDate[1] ?? null;
        $active = $param["columns"][3]["search"]["value"];
        // 驗證
        if ($name != filter_var($name, FILTER_SANITIZE_SPECIAL_CHARS)) $name = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($name, 0, 32)) $name = "___CANNOT_FIND_STRING___";
        if ($cDateStart == "") $cDateStart = "1900-01-01";
        if ($cDateFinal == "") $cDateFinal = "2050-12-31";
        if (!$this->checkParamSv->validateDate($cDateStart, 'Y-m-d')) $cDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($cDateFinal, 'Y-m-d')) $cDateFinal = "2050-12-31";
        //資料庫
        $recordsTotal = 0;
        $result = $this->settingManagementSv->getSettings(
            $recordsTotal,
            $orderColumn,
            $orderDir,
            $start,
            $length,
            $searchValue,
            $name,
            $cDateStart,
            $cDateFinal,
            $active
        );
        // 整理返回資料
        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $data[] = array(
                //一般資料
                $result[ $i ]["id"],
                $result[ $i ]["name"],
                $result[ $i ]["k"],
                $result[ $i ]["v"],
                $result[ $i ]["active"],
                $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, JSON_NUMERIC_CHECK), true);
    }
    
    public function create()
    {
        return view('admin.DataManagement.SettingManagementEdit', [
            'operdata' => "",
        ]);
    }
    
    public function edit($id)
    {
        $setting = $this->settingManagementSv->getSettingById($id);
        
        return view('admin.DataManagement.SettingManagementEdit', [
            'operdata' => $setting,
        ]);
    }
    
    public function store(Request $request)
    {
        // 取得參數與驗證
        $mode = $request->mode;
        $id = ($request->mode == 'insert') ? '' : $request->id;
        $name = $request->name;
        $k = $request->k ?? '';
        $v = $request->v ?? '';
        $active = $request->active ? GeneralConst::ACTIVE_YES : GeneralConst::ACTIVE_NO;
        // 服務層設置(以及實現各種業務上的邏輯)
        if ($mode == "insert") {
            // 新增模式
            $id = $this->settingManagementSv->insertSetting($name, $k, $v, $active, $request->user()->id);
        } else {
            // 編輯模式
            $this->settingManagementSv->modifySetting($id, $name, $k, $v, $active, $request->user()->id);
        }
        // 特殊變數需要同步到 S3
        if (preg_match("/^MASHUP_SETTING_.*$/", $k) == 1) {
            $this->settingManagementSv->syncSettingToS3();
        }
        
        // 跳轉
        return redirect('/backend/dataManagement/settingManagement/');
    }
    
}