<?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\TrackManagementService;
use Log;

class TrackManagementController extends Controller
{
    
    // 相關私有服務層調用器宣告
    private $checkParamSv;
    private $trackManagementSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->checkParamSv=new CheckParamService();
        $this->trackManagementSv = new TrackManagementService();
    }

    public function index()
    {
        // 渲染
        return view('admin.DataManagement.TrackManagement');

    }

    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"] ?? null ;

        // 驗證
        if ($keyword != filter_var($keyword, FILTER_SANITIZE_SPECIAL_CHARS)) $keyword = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($keyword, 0, 50)) $keyword = "___CANNOT_FIND_STRING___";
        
        //資料庫
        $recordsTotal = 0;

        $result=$this->trackManagementSv->getList($recordsTotal, $orderColumn, $orderDir, $start, $length, $searchValue, $keyword);

        // 整理返回資料
        $data = array();
        $registeredSession = '';
        $lunchOptions = '';
        for ($i = 0; $i < count($result); $i++) {
            
            $result[$i]["ctrEdit"]=' 
                <a class="btn _btn-warning btn-sm _fz-12" href="track/edit/'.$result[$i]["id"].'"><span class="_glyphicon _glyphicon-list"></span> 編輯 </a>
                <a class="btn btn-danger btn-sm _fz-12" onclick="return delWarning();" href="track/delete/'.$result[$i]["id"].'"><span class="_glyphicon _glyphicon-remove"></span> 刪除 </a>';

            $data[] = array(
                //一般資料
                $result[$i]["id"],
                htmlspecialchars($result[$i]["trackNo"]),
                htmlspecialchars($result[$i]["trackTitle"]),
                htmlspecialchars($result[$i]["trackLimit"]),
                $result[$i]["createDate"],
                $result[$i]["ctrEdit"],
            );
        }
        $json = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsTotal, //其實還是填入所有筆數，本次筆數可從陣列取得
            "data"            => $data,
        );
        
        // 返回
        return json_decode(json_encode($json), true);
    }

    public function create()
    {

        // 渲染
        return view('admin.DataManagement.TrackManagementEdit', [
            'operdata'      => '',
            'id'            => '',
        ]);
    }

    public function edit($id)
    {
        // 取得參數與驗證
        // 服務層取得資料(以及實現各種業務上的邏輯)
        $res = $this->trackManagementSv->getTrackDataById($id);

        // 渲染
        return view('admin.DataManagement.TrackManagementEdit', [
            'operdata'      => $res,
            'id'            => $id,
        ]);
    }
    
    public function store(Request $request)
    {
        // 取得參數(由於是內部系統因此不做後端驗證)
        
        try {
            $mode = $request->operateMode;
            $id = $request->id ?? null;
            $trackNo = $request->trackNo;
            $trackTitle = $request->trackTitle;
            $trackLimit = $request->trackLimit;

            \DB::beginTransaction();
            
            // 服務層設置(以及實現各種業務上的邏輯)
            if ($mode=='insert') {

                $this->trackManagementSv->insert(
                    $trackNo,
                    $trackTitle,
                    $trackLimit,
                );
                
            } elseif ($mode=='edit') {
    
                $this->trackManagementSv->store(
                    $id,
                    $trackNo,
                    $trackTitle,
                    $trackLimit,
                );
                
            }

            \DB::commit();

            return response()->json([
                'code' => 0,
                'message' => 'ok',
                'data' => [],
            ]);
        } catch (\Exception $e) {
            \DB::rollBack();

            return response()->json([
                'code' => 99,
                'message' => $e->getMessage().'/'.$e->getLine().'/'.$e->getFile(),
                'data' => [],
            ]);
        }

        // $this->referralTagManagementSv->modifyreferralTagByReferralAndTagIds($id, $hidTag);
        // 跳轉
        return redirect('/backend/dataManagement/track');
    }

    public function delete($id)
    {
        // 取得參數與驗證
        // 服務層取得資料(以及實現各種業務上的邏輯)
        $this->trackManagementSv->deleteDataById($id);

        // 跳轉
        return redirect('/backend/dataManagement/track');
    }
}