<?php

namespace App\Http\Services\Backend\DataManagement;

use App\Http\Services\ConstDef\GeneralConst;
use App\Models\Web\Settings;

class SettingManagementService
{
    
    private $settingManagementDb;
    private $basedir;
    
    public function __construct()
    {
        date_default_timezone_set("Asia/Taipei");
        $this->settingManagementDb = new Settings();
        $this->basedir = preg_replace('/\/app\/.*/', '/public/', __DIR__);
    }
    
    public function getSettings(
        &$cnt = 0,
        $orderColumn,
        $orderDir,
        $start,
        $length,
        $searchValue,
        $name,
        $cDateStart,
        $cDateFinal,
        $active
    )
    {
        // 選欄位
        $activeStr = '';
        foreach (GeneralConst::$activeMap as $k => $v) {
            $activeStr .= ' when \'' . $k . '\' then \'' . $v . '\'';
        }
        $settings = $this->settingManagementDb
            ->select([
                'id',
                \DB::raw("CONCAT('<a href=\"settingManagement/edit/', id, '\">', name, '</a>') as name"),
                'k',
                'v',
                \DB::raw("(case active $activeStr end) as active"),
                'cdate',
                'mdate',
                \DB::raw("(select name from users where id=settings.oid) as oid"),
            ]);
        // 過濾搜尋條件
        $settings = $settings
            ->where('name', 'LIKE', '%' . $name . '%');
        if ($active != '') $settings = $settings->where('active', '=', $active);
        $settings = $settings->where('cdate', '>=', $cDateStart . ' 00:00:00');
        $settings = $settings->where('cdate', '<=', $cDateFinal . ' 23:59:59');
        // 取總筆數
        $cnt = $settings->count();
        // 排序
        $settings = $settings
            ->orderByRaw((int)$orderColumn . ' ' . $orderDir);
        // 彙整
        // 分頁
        $settings = $settings
            ->skip($start)->take($length);
        // 實際取資料
        $settings = $settings
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $settings;
    }
    
    public function getSettingById($id)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $setting = $this->settingManagementDb->select([
            'id',
            'name',
            'k',
            'v',
            'active',
            'cdate',
            'mdate',
            \DB::raw("(select name from users where id=settings.oid) as oid"),
        ])
            ->where('id', $id)
            ->first()
            ->toArray();
        
        // 整理返回值並返回
        return $setting;
    }
    
    public function insertSetting($name, $k, $v, $active, $oid)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $this->settingManagementDb
            ->insert([
                'name'   => $name,
                'k'      => $k,
                'v'      => $v,
                'active' => $active,
                'cdate'  => date('Y-m-d H:i:s'),
                'mdate'  => date('Y-m-d H:i:s'),
                'oid'    => $oid,
            ]);
        $id = \DB::getPdo()->lastInsertId();
        
        // 整理返回值並返回
        return $id;
    }
    
    public function modifySetting($id, $name, $k, $v, $active, $oid)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $res = $this->settingManagementDb
            ->where('id', $id)
            ->update([
                'name'   => $name,
                'k'      => $k,
                'v'      => $v,
                'active' => $active,
                'mdate'  => date('Y-m-d H:i:s'),
                'oid'    => $oid,
            ]);
        
        // 整理返回值並返回
        return $res;
    }
    
    // 外部服務取得設定
    public function getSetting()
    {
        $res = $this->settingManagementDb->select(['k', 'v'])->where('active', GeneralConst::ACTIVE_YES)->get()->toArray();
        $setting = [];
        foreach ($res as $r) $setting[ $r['k'] ] = $r['v'];
        
        return $setting;
    }
    
    // 外部服務取得設定
    public function setSetting($k, $v)
    {
        $this->settingManagementDb
            ->where('k', $k)
            ->where('active', GeneralConst::ACTIVE_YES)
            ->update([
                'v'     => $v,
                'mdate' => date('Y-m-d H:i:s'),
                'oid'   => 1, // 腳本更改視為管理員更改
            ]);
        
        return true;
    }
    
    // 外部服務取得設定
    public function syncSettingToS3()
    {
        $res = $this->settingManagementDb
            ->select(['k', 'v'])
            ->where('active', GeneralConst::ACTIVE_YES)
            ->where('k', 'like', 'MASHUP_SETTING_%')
            ->get()
            ->toArray();
        $setting = [];
        foreach ($res as $r) $setting[ $r['k'] ] = json_decode($r['v'], true);
        // 寫入 S3 (不保存在本地)
        $s3 = new \Aws\S3\S3Client([
            'credentials' => [
                'key'    => env('AWS_APP_KEY'),
                'secret' => env('AWS_APP_SECRET'),
            ],
            'region'      => env('AWS_S3_REGION'),
            'version'     => 'latest',
        ]);
        $s3->putObject([
            'ACL'         => 'public-read',
            'Body'        => json_encode($setting, JSON_UNESCAPED_UNICODE),
            'Bucket'      => env('AWS_S3_BUCKET'),
            'ContentType' => 'application/json; charset=utf-8',
            'Key'         => env('AWS_S3_NAMESPACE') . '/' . substr(GeneralConst::JSON_BASE_SETTING, 2),
        ]);
        unset($s3);
        
        return true;
    }
    
}