<?php

namespace App\Http\Controllers\Backend\DataManagement;

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

class EventManagementController
{
    // 相關私有服務層調用器宣告
    private $eventManagementSv;
    private $checkParamSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->eventManagementSv = new EventManagementService();
        $this->checkParamSv = new CheckParamService();
        // 時區調整
        date_default_timezone_set("Asia/Taipei");
    }
    
    public function index()
    {
        // 渲染
        return view('admin.DataManagement.EventManagement', [
            'archive' => GeneralConst::$archiveMap,
        ]);
    }
    
    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"];
        $eventDate = explode("\n", $param["columns"][2]["search"]["value"]);
        $eventDateStart = $eventDate[0] ?? null;
        $eventDateFinal = $eventDate[1] ?? null;
        $archive = $param["columns"][3]["search"]["value"];
        // 驗證
        if ($name != filter_var($name, FILTER_SANITIZE_SPECIAL_CHARS)) $name = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($name, 0, 16)) $name = "___CANNOT_FIND_STRING___";
        if ($eventDateStart == "") $eventDateStart = "1900-01-01";
        if ($eventDateFinal == "") $eventDateFinal = "2050-12-31";
        if (!$this->checkParamSv->validateDate($eventDateStart, 'Y-m-d')) $eventDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($eventDateFinal, 'Y-m-d')) $eventDateFinal = "2050-12-31";
        //資料庫
        $recordsTotal = 0;
        $result = $this->eventManagementSv->getEvents(
            $recordsTotal,
            $orderColumn,
            $orderDir,
            $start,
            $length,
            $searchValue,
            $name,
            $eventDateStart,
            $eventDateFinal,
            $archive
        );
        // 整理返回資料
        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $data[] = array(
                //一般資料
                $result[ $i ]["chk"],
                $result[ $i ]["id"],
                $result[ $i ]["name"],
                $result[ $i ]["cnt"],
                $result[ $i ]["date_begin"],
                $result[ $i ]["date_final"],
                $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 archive(Request $request)
    {
        // 取得參數
        $grp = $request->input('grp', []);
        // 執行
        if (count($grp) > 0) $this->eventManagementSv->archive($grp);
        
        // 返回
        return response()->json(["succ" => true, "err" => '']);
    }
    
    public function unarchive(Request $request)
    {
        // 取得參數
        $grp = $request->input('grp', []);
        // 執行
        if (count($grp) > 0) $this->eventManagementSv->unarchive($grp);
        
        // 返回
        return response()->json(["succ" => true, "err" => '']);
    }
    
    public function clear(Request $request)
    {
        // 取得參數
        $grp = $request->input('grp', []);
        // 執行
        if (count($grp) > 0) $this->eventManagementSv->clear($grp);
        
        // 返回
        return response()->json(["succ" => true, "err" => '']);
    }
    
    public function create()
    {
        // 渲染
        return view('admin.DataManagement.EventManagementEdit', [
            'operdata' => "",
        ]);
    }
    
    public function edit($id)
    {
        // 取得參數與驗證
        // 服務層取得資料(以及實現各種業務上的邏輯)
        $event = $this->eventManagementSv->getEventById($id);
        
        // 渲染
        return view('admin.DataManagement.EventManagementEdit', [
            'operdata' => $event,
        ]);
    }
    
    public function saveImg(Request $request)
    {
        $arrayBuffer = $request->image;
        $dirname = 'kv';
        // 圖片還原
        $binary = "";
        for ($index = 0; $index < count($arrayBuffer); $index++) $binary = $binary . pack("C*", $arrayBuffer[ $index ]);
        // 路徑命名
        $date = date('Y-m-d');
        if (!file_exists($dirname)) mkdir($dirname, 0777, true);
        if (!file_exists($dirname . '/' . $date)) mkdir($dirname . '/' . $date, 0777, true);
        // 保存圖片
        $time = time();
        $fp = fopen($dirname . '/' . $date . '/' . $time . '.jpg', 'w');
        fwrite($fp, $binary);
        fclose($fp);
        // 返回
        $json = array(
            "url" => env('APP_URL') . $dirname . '/' . $date . '/' . $time . '.jpg',
            "kv"  => $dirname . '/' . $date . '/' . $time . '.jpg',
        );
        
        return json_decode(json_encode($json, JSON_NUMERIC_CHECK), true);
    }
    
    public function store(Request $request)
    {
        // 取得參數與驗證
        $mode = $request->mode;
        $id = ($request->mode == 'insert') ? '' : $request->id;
        $name = $request->name;
        $kv = $request->kv ?? '';
        $date_begin = $request->date_begin;
        $date_final = $request->date_final;
        $email = $request->email;
        $tel = $request->tel;
        $items = $request->items ?? [];
        if ($kv == '') {
            return Redirect::back()->withErrors("需要上傳主視覺");
        }
        if (count($items) == 0) {
            return Redirect::back()->withErrors("需要有獎項");
        }
        // 服務層設置(以及實現各種業務上的邏輯)
        if ($mode == "insert") {
            // 新增模式
            $id = $this->eventManagementSv->insertEvent($name, $kv, $date_begin, $date_final, $email, $tel, $request->user()->id);
            foreach ($items['new'] as $item) $this->eventManagementSv->insertItem($id, $item['name'], $item['is_ide'] ?? 'N', $item['id_acc'] ?? 'N');
    
        } else {
            // 編輯模式
            $this->eventManagementSv->modifyEvent($id, $name, $kv, $date_begin, $date_final, $email, $tel, $request->user()->id);
            foreach ($items['new'] as $item) $this->eventManagementSv->insertItem($id, $item['name'], $item['is_ide'] ?? 'N', $item['id_acc'] ?? 'N');
            foreach ($items['edit'] as $k => $item) $this->eventManagementSv->modifyItem($k, $id, $item['name']);
        }
        
        // 跳轉
        return redirect('/backend/dataManagement/eventManagement/edit/' . $id);
    }
    
    public function getItems($eid)
    {
        $json = $result = $this->eventManagementSv->getItems($eid);
        
        // 返回
        return json_decode(json_encode($json, JSON_NUMERIC_CHECK), true);
    }
    
}