<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use Config\Database;

class SettingsController extends BaseController
{
    public function index()
    {
        $rows = Database::connect()->table('settings')->get()->getResultArray();
        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['group']][$row['key']] = $row['is_encrypted'] ? '••••••••' : $row['value'];
        }
        return $this->jsonSuccess($grouped);
    }

    public function creditCosts()
    {
        $rows = Database::connect()->table('credit_costs')->get()->getResultArray();
        return $this->jsonSuccess($rows);
    }

    public function updateCreditCost(string $action)
    {
        $input = $this->request->getJSON(true);
        $cost = (int) ($input['credit_cost'] ?? 0);
        if ($cost < 0) {
            return $this->jsonValidationError(['credit_cost' => 'Must be a non-negative integer.']);
        }

        $db = Database::connect();
        $existing = $db->table('credit_costs')->where('action', $action)->get()->getRow();
        if (! $existing) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => "Unknown credit action: {$action}"]], 404);
        }

        $db->table('credit_costs')->where('id', $existing->id)->update(['credit_cost' => $cost, 'updated_at' => date('Y-m-d H:i:s')]);

        return $this->jsonSuccess(['message' => 'Credit cost updated.']);
    }

    public function update(string $group)
    {
        $input = $this->request->getJSON(true);
        $db = Database::connect();

        foreach ($input as $key => $value) {
            $existing = $db->table('settings')->where('group', $group)->where('key', $key)->get()->getRow();
            // SMTP password is the one field in this system worth flagging
            // as sensitive so index()'s masking (••••••••) kicks in for it.
            $isEncrypted = ($group === 'smtp' && $key === 'password') ? 1 : 0;

            if ($existing) {
                $db->table('settings')->where('id', $existing->id)->update(['value' => $value, 'is_encrypted' => $isEncrypted, 'updated_at' => date('Y-m-d H:i:s')]);
            } else {
                $db->table('settings')->insert(['group' => $group, 'key' => $key, 'value' => $value, 'is_encrypted' => $isEncrypted, 'updated_at' => date('Y-m-d H:i:s')]);
            }
        }

        return $this->jsonSuccess(['message' => 'Settings updated.']);
    }

    /**
     * Sends a live test email using whatever SMTP settings are currently
     * saved (via EmailChannel's settings-table lookup), so the Super Admin
     * can confirm the configuration works before relying on it for real
     * notifications.
     */
    public function testSmtp()
    {
        $input = $this->request->getJSON(true);
        $to = $input['to'] ?? null;
        if (! $to) {
            return $this->jsonValidationError(['to' => 'A recipient email is required.']);
        }

        $sent = (new \App\Libraries\NotificationChannels\EmailChannel())->send(
            $to,
            'Job Portal — SMTP Test',
            '<p>This is a test email sent from Admin → Settings → SMTP. If you received this, your configuration is working.</p>'
        );

        return $sent
            ? $this->jsonSuccess(['message' => 'Test email sent.'])
            : $this->jsonError([['code' => 'SMTP_TEST_FAILED', 'message' => 'Failed to send — check your SMTP settings.']], 422);
    }
}
