<?php

namespace App\Controllers;

use App\Models\SystemSettingModel;

class SettingsController extends BaseController
{
    private function validateJWT($token)
    {
        $tokenParts = explode('.', $token);
        if (count($tokenParts) !== 3) return false;

        $payload = base64_decode(str_replace(['-', '_'], ['+', '/'], $tokenParts[1]));
        $signatureProvided = $tokenParts[2];

        $secret = env('JWT_SECRET', 'kopmart_super_secret_jwt_key_2026_xyz123_abc456_qwe789');
        $signature = hash_hmac('sha256', $tokenParts[0] . "." . $tokenParts[1], $secret, true);
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

        if ($base64UrlSignature !== $signatureProvided) return false;

        $payloadDecoded = json_decode($payload, true);
        if ($payloadDecoded['exp'] < time()) return false; // expired

        return $payloadDecoded;
    }

    public function index()
    {
        $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
        if (!$authHeader) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Token otorisasi diperlukan'])->setStatusCode(401);
        }

        $token = str_replace('Bearer ', '', $authHeader);
        $decoded = $this->validateJWT($token);
        if (!$decoded || $decoded['role_id'] != 1) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Otorisasi ditolak'])->setStatusCode(403);
        }

        $settingModel = new SystemSettingModel();
        $settings = $settingModel->findAll();

        $data = [];
        foreach ($settings as $setting) {
            $data[$setting['key_name']] = $setting['key_value'];
        }

        // Mask password
        if (!empty($data['smtp_pass'])) {
            $data['smtp_pass'] = '********';
        }

        return $this->response->setJSON([
            'status' => 'success',
            'data' => $data
        ]);
    }

    public function update()
    {
        $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
        if (!$authHeader) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Token otorisasi diperlukan'])->setStatusCode(401);
        }

        $token = str_replace('Bearer ', '', $authHeader);
        $decoded = $this->validateJWT($token);
        if (!$decoded || $decoded['role_id'] != 1) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Otorisasi ditolak'])->setStatusCode(403);
        }

        $settingModel = new SystemSettingModel();

        $fields = ['app_name', 'smtp_from', 'active_year', 'smtp_host', 'smtp_port', 'smtp_crypto', 'smtp_user'];
        foreach ($fields as $field) {
            $val = $this->request->getVar($field);
            if ($val !== null) {
                $settingModel->setSetting($field, $val);
            }
        }

        $smtpPass = $this->request->getVar('smtp_pass');
        if ($smtpPass !== null && $smtpPass !== '********' && $smtpPass !== '') {
            $settingModel->setSetting('smtp_pass', $smtpPass);
        }

        // Add log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $decoded['uid'],
            'action' => 'Perbarui Pengaturan Sistem',
            'notes' => 'Admin memperbarui konfigurasi sistem (termasuk SMTP).',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Pengaturan berhasil disimpan'
        ]);
    }
}
