<?php

namespace App\Http\Services\Backend\DataManagement;

use App\Http\Services\ConstDef\GeneralConst;
use App\Models\Web\Event;
use App\Models\Web\Item;
use App\Models\Web\Submit;

class EventManagementService
{
    // 相關私有 model 調用器宣告
    private $eventManagementDb;
    private $itemManagementDb;
    private $submitManagementDb;
    
    public function __construct()
    {
        date_default_timezone_set("Asia/Taipei");
        // 建構 model 調用器
        $this->eventManagementDb = new Event();
        $this->itemManagementDb = new Item();
        $this->submitManagementDb = new Submit();
    }
    
    public function getEvents(
        &$cnt = 0,
        $orderColumn,
        $orderDir,
        $start,
        $length,
        $searchValue,
        $name,
        $eventDateStart,
        $eventDateFinal,
        $archive
    )
    {
        // 選欄位
        $archiveStr = '';
        foreach (GeneralConst::$archiveMap as $k => $v) {
            $archiveStr .= ' when \'' . $k . '\' then \'' . $v . '\'';
        }
        
        $events = $this->eventManagementDb
            ->select([
                \DB::raw("CONCAT('<input class=\"form-check-input\" type=\"checkbox\" name=\"grp[', id, ']\" value=\"\">') as chk"),
                'id',
                \DB::raw("CONCAT('<a href=\"eventManagement/edit/', id, '\">', name, '</a>') as name"),
                \DB::raw("(select count(*) from items where eid=events.id) as cnt"),
                'date_begin',
                'date_final',
                'cdate',
                'mdate',
                \DB::raw("(select name from users where id=events.oid) as oid"),
            ]);
        // 過濾搜尋條件
        $events = $events
            ->where('name', 'LIKE', '%' . $name . '%');
        if ($archive != '') $events = $events->where('archive', '=', $archive);
        $events = $events->where('date_begin', '>=', $eventDateStart . ' 00:00:00');
        $events = $events->where('date_final', '<=', $eventDateFinal . ' 23:59:59');
        // 取總筆數
        $cnt = $events->count();
        // 排序
        $events = $events
            ->orderByRaw((int)$orderColumn . ' ' . $orderDir);
        // 彙整
        // 分頁
        $events = $events
            ->skip($start)->take($length);
        // 實際取資料
        $events = $events
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $events;
    }
    
    public function getItems($eid)
    {
        $items = $this->itemManagementDb
            ->select([
                'id',
                'eid',
                'name',
                'is_ide',
                'id_acc',
                \DB::raw("CONCAT('" . env('APP_URL') . "', 'main/?h=', HEX(AES_ENCRYPT(TO_BASE64(CONCAT(eid, ',', id)), '" . env('KK') . "'))) as link"),
            ])
            ->where('eid', $eid)
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $items;
    }
    
    public function archive($grp)
    {
        $this->eventManagementDb
            ->whereIn('id', $grp)
            ->update([
                'archive' => GeneralConst::ARCHIVE_YES,
            ]);
        
        // 整理返回值並返回
        return true;
    }
    
    public function unarchive($grp)
    {
        $this->eventManagementDb
            ->whereIn('id', $grp)
            ->update([
                'archive' => GeneralConst::ARCHIVE_NO,
            ]);
        
        // 整理返回值並返回
        return true;
    }
    
    public function clear($grp)
    {
        // 找出所有獎項ID
        $items = $this->itemManagementDb->select([
            'id',
        ])
            ->whereIn('eid', $grp)
            ->get()
            ->toArray();
        $iid = [];
        foreach ($items as $i) $iid[] = $i['id'];
        // 找出所有獎項ID下的申報資料
        $submits = $this->submitManagementDb->select([
            GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'],
            GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'],
            GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'],
            GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'],
        ])
            ->whereIn('iid', $iid)
            ->get()
            ->toArray();
        foreach ($submits as $s) {
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] ])) unlink($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] ]);
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] ])) unlink($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] ]);
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] ])) unlink($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] ]);
            if (file_exists($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] ])) unlink($s[ GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] ]);
        }
        // 刪除
        $this->submitManagementDb
            ->whereIn('iid', $iid)
            ->delete();
        
        return true;
    }
    
    public function getEventById($id)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $events = $this->eventManagementDb->select([
            'id',
            'name',
            'kv',
            'date_begin',
            'date_final',
            'email',
            'tel',
            'archive',
            'cdate',
            'mdate',
            \DB::raw("(select name from users where id=events.oid) as oid"),
        ])
            ->where('id', $id)
            ->first()
            ->toArray();
        
        // 整理返回值並返回
        return $events;
    }
    
    public function insertEvent($name, $kv, $date_begin, $date_final, $email, $tel, $oid)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $this->eventManagementDb
            ->insert([
                'name'       => $name,
                'kv'         => $kv,
                'date_begin' => $date_begin,
                'date_final' => $date_final,
                'email'      => $email,
                'tel'        => $tel,
                'cdate'      => date('Y-m-d H:i:s'),
                'oid'        => $oid,
            ]);
        $id = \DB::getPdo()->lastInsertId();
        
        // 整理返回值並返回
        return $id;
    }
    
    public function modifyEvent($id, $name, $kv, $date_begin, $date_final, $email, $tel, $oid)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $res = $this->eventManagementDb
            ->where('id', $id)
            ->update([
                'name'       => $name,
                'kv'         => $kv,
                'date_begin' => $date_begin,
                'date_final' => $date_final,
                'email'      => $email,
                'tel'        => $tel,
                'mdate'      => date('Y-m-d H:i:s'),
                'oid'        => $oid,
            ]);
        
        // 整理返回值並返回
        return $res;
    }
    
    public function insertItem($eid, $name, $is_ide, $id_acc)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $this->itemManagementDb
            ->insert([
                'eid'    => $eid,
                'name'   => $name,
                'is_ide' => $is_ide,
                'id_acc' => $id_acc,
            ]);
        $id = \DB::getPdo()->lastInsertId();
        
        // 整理返回值並返回
        return $id;
    }
    
    public function modifyItem($id, $eid, $name)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $res = $this->itemManagementDb
            ->where('id', $id)
            ->where('eid', $eid)
            ->update([
                'name' => $name
            ]);
        
        // 整理返回值並返回
        return $res;
    }
    
}