<?php

namespace App\Http\Controllers\Backend\DataManagement;

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

class SubmitManagementController
{
    // 相關私有服務層調用器宣告
    private $submitManagementSv;
    private $checkParamSv;
    
    public function __construct()
    {
        // 建構服務層調用器
        $this->submitManagementSv = new SubmitManagementService();
        $this->checkParamSv = new CheckParamService();
        // 時區調整
        date_default_timezone_set("Asia/Taipei");
    }
    
    public function index()
    {
        // 渲染
        return view('admin.DataManagement.SubmitManagement', [
            'duplicate' => GeneralConst::$duplicateMap,
            'events'    => $this->submitManagementSv->getEvents(),
        ]);
    }
    
    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"];
        //客製化搜尋欄位
        $submitDate = explode("\n", $param["columns"][1]["search"]["value"]);
        $submitDateStart = $submitDate[0] ?? null;
        $submitDateFinal = $submitDate[1] ?? null;
        $iid = $param["columns"][2]["search"]["value"];
        $searchcol = $param["columns"][3]["search"]["value"];
        $duplicate = $param["columns"][4]["search"]["value"];
        // 驗證
        if ($submitDateStart == "") $submitDateStart = "1900-01-01";
        if ($submitDateFinal == "") $submitDateFinal = "2050-12-31";
        if ($iid == "") $iid = 0;
        if (!$this->checkParamSv->validateDate($submitDateStart, 'Y-m-d')) $submitDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($submitDateFinal, 'Y-m-d')) $submitDateFinal = "2050-12-31";
        if ($searchcol != filter_var($searchcol, FILTER_SANITIZE_SPECIAL_CHARS)) $searchcol = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($searchcol, 0, 128)) $searchcol = "___CANNOT_FIND_STRING___";
        //資料庫
        $recordsTotal = 0;
        $result = $this->submitManagementSv->getSubmits(
            $recordsTotal,
            $orderColumn,
            $orderDir,
            $start,
            $length,
            $searchValue,
            $submitDateStart,
            $submitDateFinal,
            $iid,
            $searchcol,
            $duplicate
        );
        // 整理返回資料
        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $data[] = array(
                //一般資料
                $result[ $i ]["id"],
                $result[ $i ]["event_name"],
                $result[ $i ]["item_name"],
                $result[ $i ]["name"],
                $result[ $i ]["identity"],
                $result[ $i ]["add_host"],
                $result[ $i ]["add_contact"],
                $result[ $i ]["tel"],
                $result[ $i ][ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] ],
                $result[ $i ][ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] ],
                $result[ $i ][ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] ],
                $result[ $i ][ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] ],
                $result[ $i ]["cdate"],
            );
        }
        $json = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsTotal, //其實還是填入所有筆數，本次筆數可從陣列取得
            "data"            => $data,
        );
        
        // 返回
        return json_decode(json_encode($json, JSON_NUMERIC_CHECK), true);
    }
    
    public function getItems($eid)
    {
        $json = $this->submitManagementSv->getItems($eid);
        
        // 整理返回值並返回
        return json_decode(json_encode($json, JSON_NUMERIC_CHECK), true);
    }
    
    public function getZip($param)
    {
        // 取得參數
        if ($param == null) exit();
        $param = explode('|', $param);
        //客製化搜尋欄位
        $submitDateStart = $param[0];
        $submitDateFinal = $param[1];
        $iid = $param[2];
        $searchcol = $param[3];
        $duplicate = $param[4];
        // 驗證
        if ($submitDateStart == "") $submitDateStart = "1900-01-01";
        if ($submitDateFinal == "") $submitDateFinal = "2050-12-31";
        if (!$this->checkParamSv->validateDate($submitDateStart, 'Y-m-d')) $submitDateStart = "1900-01-01";
        if (!$this->checkParamSv->validateDate($submitDateFinal, 'Y-m-d')) $submitDateFinal = "2050-12-31";
        if ($iid == "") $iid = 0;
        if ($searchcol != filter_var($searchcol, FILTER_SANITIZE_SPECIAL_CHARS)) $searchcol = "___CANNOT_FIND_STRING___";
        if (!$this->checkParamSv->LenMToN($searchcol, 0, 128)) $searchcol = "___CANNOT_FIND_STRING___";
        // 路徑命名
        $dirname = 'working';
        $date = date("YmdHis");
        if (!file_exists($dirname)) mkdir($dirname, 0777, true);
        if (!file_exists($dirname . '/' . $date)) mkdir($dirname . '/' . $date, 0777, true);
        $basepath = $dirname . '/' . $date . '/';
        $excel_name = 'REPORT.xlsx';
        $zip_name = 'REPORT' . $date . '.zip';
        $report_files = [];
        // 製作 EXCEL
        $title = [
            'ID',
            '活動名稱',
            '獎別',
            '申請人姓名',
            '身分證號',
            '戶籍地址',
            '通訊地址',
            '電話',
            '建立時間',
        ];
        $submits = $this->submitManagementSv->getExportSubmits(
            $submitDateStart,
            $submitDateFinal,
            $iid,
            $searchcol,
            $duplicate
        );
        $excels = [];
        foreach ($submits as $s) {
            $excels[] = [
                'id'          => $s['id'],
                'event_name'  => $s['event_name'],
                'item_name'   => $s['item_name'],
                'name'        => $s['name'],
                'identity'    => $s['identity'],
                'add_host'    => $s['add_host'],
                'add_contact' => $s['add_contact'],
                'tel'         => $s['tel'],
                'cdate'       => $s['cdate'],
            ];
        }
        $this->submitManagementSv->getExcel($title, $excels, $basepath . $excel_name);
        $report_files[] = $basepath . $excel_name;
        // 取得相關素材
        foreach ($submits as $s) {
            // 依照該身分證字號創建資料夾
            $mypath = $basepath . $s['identity'] . '/';
            if (!file_exists($mypath)) mkdir($mypath, 0777, true);
            // 逐一拷貝
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] ])) {
                copy($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] ], $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['ext']);
                $report_files[] = $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['ext'];
            }
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] ])) {
                copy($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] ], $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['ext']);
                $report_files[] = $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['ext'];
            }
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] ])) {
                copy($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] ], $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['ext']);
                $report_files[] = $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['ext'];
            }
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] ])) {
                copy($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] ], $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['ext']);
                $report_files[] = $mypath . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['zip_file'] . substr($date, 2, 6) . '-' . $s['id'] . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['ext'];
            }
        }
        // 製作壓縮檔
        foreach (glob($dirname . '/*.zip') as $f) if (is_file($f)) unlink($f); // 殺掉前幾次的舊匯出檔案
        $zip = new ZipArchive;
        if ($zip->open($dirname . '/' . $zip_name, ZipArchive::CREATE) === true) {
            foreach ($report_files as $f) $zip->addFile($f, str_replace($dirname . '/', '', $f));
            $zip->close();
        }
        $headers = array(
            'Content-Type' => 'application/octet-stream',
        );
        // 刪除文件夾
        $this->rrmdir($basepath);
        
        return response()->download($dirname . '/' . $zip_name, $zip_name, $headers);
    }
    
    public function rrmdir($dir)
    {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (is_dir($dir . DIRECTORY_SEPARATOR . $object) && !is_link($dir . "/" . $object))
                        $this->rrmdir($dir . DIRECTORY_SEPARATOR . $object);
                    else
                        unlink($dir . DIRECTORY_SEPARATOR . $object);
                }
            }
            rmdir($dir);
        }
    }
    
}