<?php

namespace App\Http\Controllers\Backend\DataManagement;

use App\Http\Services\CheckParamService;
use Illuminate\Http\Request;
use App\Http\Services\Backend\DataManagement\UrlManagementService;
use App\Http\Controllers\Controller;
use App\Http\Services\ConstDef\GeneralConst;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;

class UrlManagementController extends Controller
{
    
    // 相關私有服務層調用器宣告
    private $urlManagementSv;
    private $checkParamSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->urlManagementSv = new UrlManagementService();
        $this->checkParamSv = new CheckParamService();
        // 時區調整
        date_default_timezone_set("Asia/Taipei");
    }
    
    public function index(Request $request)
    {
        // 渲染
        return view('admin.DataManagement.UrlManagement', [
            'titles' => $this->urlManagementSv->getTitles($request->user()->id),
            'valids' => $this->urlManagementSv->getValids(),
        ]);
    }
    
    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"];
        //客製化搜尋欄位
        $title = $param["columns"][1]["search"]["value"];
        $memo = $param["columns"][2]["search"]["value"];
        $createDate = explode("\n", $param["columns"][3]["search"]["value"]);
        $createDateStart = $createDate[0] ?? null;
        $createDateFinal = $createDate[1] ?? null;
        $valid = $param["columns"][4]["search"]["value"];
        // 驗證
        if ($title != filter_var($title, FILTER_SANITIZE_SPECIAL_CHARS)) $title = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($title, 0, 20)) $title = "___CANNOT_FIND_STRING___";
        if ($memo != filter_var($memo, FILTER_SANITIZE_SPECIAL_CHARS)) $memo = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($memo, 0, 20)) $memo = "___CANNOT_FIND_STRING___";
        if ($createDateStart == "") $createDateStart = "1900-01-01";
        if ($createDateFinal == "") $createDateFinal = "2050-12-31";
        if (!$this->checkParamSv->validateDate($createDateStart, 'Y-m-d')) $createDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($createDateFinal, 'Y-m-d')) $createDateFinal = "2050-12-31";
        if (!isset(GeneralConst::$urlMap[ $valid ])) $valid = GeneralConst::URL_OK;
        //資料庫
        $recordsTotal = 0;
        $result = $this->urlManagementSv->getUrls(
            $recordsTotal,
            $orderColumn,
            $orderDir,
            $start,
            $length,
            $searchValue,
            $title,
            $memo,
            $createDateStart,
            $createDateFinal,
            $valid,
            $request->user()->id
        );
        // 整理返回資料
        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $data[] = array(
                //一般資料
                $result[ $i ]["serno"],
                $result[ $i ]["title"],
                $result[ $i ]["url"],
                $result[ $i ]["code"],
                $result[ $i ]["memo"],
                $result[ $i ]["pv"],
                $result[ $i ]["valid"],
                $result[ $i ]["edit"],
                $result[ $i ]["qrcode"],
            );
        }
        $json = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsTotal, //其實還是填入所有筆數，本次筆數可從陣列取得
            "data"            => $data,
        );
        
        // 返回
        return json_decode(json_encode($json, JSON_NUMERIC_CHECK), true);
    }
    
    public function qrcode($code)
    {
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename="' . $code . '.png"');
        header('Content-Transfer-Encoding: binary');
        header('Content-type: image/png');
        $options = new QROptions([
            'version'     => 2,
            'outputType'  => QRCode::OUTPUT_IMAGE_PNG,
            'imageBase64' => false,
        ]);
        echo (new QRCode($options))->render(env('ORL_URL') . $code);
    }
    
    public function create(Request $request)
    {
        // 服務層取得資料(以及實現各種業務上的邏輯)
        $titles = $this->urlManagementSv->getTitles($request->user()->id);
        
        // 渲染
        return view('admin.DataManagement.UrlManagementEdit', [
            'titles'   => $titles,
            'operdata' => "",
        ]);
    }
    
    public function edit($id, Request $request)
    {
        // 取得參數與驗證
        // 服務層取得資料(以及實現各種業務上的邏輯)
        $operdata = $this->urlManagementSv->getUrlById($id, $request->user()->id);
        $titles = $this->urlManagementSv->getTitles($request->user()->id);
        
        // 渲染
        return view('admin.DataManagement.UrlManagementEdit', [
            'titles'   => $titles,
            'operdata' => $operdata,
        ]);
    }
    
    public function store(Request $request)
    {
        // 取得參數與驗證
        $mode = $request->mode;
        $id = ($request->mode == 'insert') ? '' : $request->serno;
        $title = $request->title;
        $url = $request->url;
        $memo = $request->memo;
        $valid = ($request->valid == 'on') ? GeneralConst::URL_OK : GeneralConst::URL_NO;
        // 服務層設置(以及實現各種業務上的邏輯)
        if ($mode == "insert") {
            $code = $this->urlManagementSv->getCode();
            // 新增模式
            $id = $this->urlManagementSv->insertUrl($title, $url, $code, $memo, $valid, $request->user()->id);
        } else {
            // 編輯模式
            $this->urlManagementSv->modifyUrl($id, $title, $url, $memo, $valid);
        }
        
        // 跳轉
        return redirect('/backend/dataManagement/urlManagement');
    }
    
    public function export(Request $request)
    {
        // 取得參數
        $param = $_POST;
        if ($param == null) exit();
        // 驗證
        if ($param['title'] != filter_var($param['title'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['title'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['title'], 0, 20)) $param['title'] = "___CANNOT_FIND_STRING___";
        if ($param['memo'] != filter_var($param['memo'], FILTER_SANITIZE_SPECIAL_CHARS)) $param['memo'] = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($param['memo'], 0, 20)) $param['memo'] = "___CANNOT_FIND_STRING___";
        if ($param['createDateStart'] == "") $param['createDateStart'] = "1900-01-01";
        if ($param['createDateFinal'] == "") $param['createDateFinal'] = "2050-12-31";
        if (!$this->checkParamSv->validateDate($param['createDateStart'], 'Y-m-d')) $param['createDateStart'] = "1900-01-01";
        if (!$this->checkParamSv->validateDate($param['createDateFinal'], 'Y-m-d')) $param['createDateFinal'] = "2050-12-31";
        if (!isset(GeneralConst::$urlMap[ $param['valid'] ])) $param['valid'] = GeneralConst::URL_OK;
        // 製作
        $title = [
            '網址',
            '短網址',
            '備註',
            '有效否',
            '造訪次',
        ];
        $urls = $this->urlManagementSv->getExportUrls($param, $request->user()->id);
        $this->urlManagementSv->downloadExcel($title, $urls, date("YmdHis") . '-REPORT');
    }
    
}