<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use Core\Controller;
use Core\Settings;
use Core\Session;

/**
 * Company profile / settings — editable only by admin roles.
 * Stores company_name, tin, vat, address, city, country, phone, email, website, logo, etc.
 * in the ai_settings table via Core\Settings.
 *
 * URL: /CompanySettings
 */
final class CompanySettingsController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    /** Allowed keys exposed through the form. */
    private const COMPANY_KEYS = [
        'company_name',
        'company_tin',
        'company_vat',
        'company_address',
        'company_city',
        'company_country',
        'company_phone',
        'company_email',
        'company_website',
        'company_logo_url',
        'company_reg_number',
        'company_bank_name',
        'company_bank_account',
    ];

    public function index(): void
    {
        $u = Session::user();
        $role = $u['role_code'] ?? '';
        if (!in_array($role, ['admin', 'executive'], true)) {
            Session::flash('error', 'Access denied — admin only.');
            header('Location: ' . url('/Home'));
            exit;
        }

        $data = [];
        foreach (self::COMPANY_KEYS as $k) {
            $data[$k] = Settings::get($k, '');
        }

        // defaults for fresh installs
        if (empty($data['company_name'])) {
            $data['company_name'] = APP_NAME;
        }

        $this->render('company-settings/index', [
            'data'   => $data,
            'flash'  => Session::flash('cs_msg'),
            'title'  => 'Company Settings',
        ]);
    }

    public function save(): void
    {
        $u = Session::user();
        $role = $u['role_code'] ?? '';
        if (!in_array($role, ['admin', 'executive'], true)) {
            json_response(['error' => 'Access denied.'], 403);
        }

        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            json_response(['error' => 'Method not allowed.'], 405);
        }

        $userId = (int) ($u['user_id'] ?? 0);
        $changed = [];

        foreach (self::COMPANY_KEYS as $k) {
            $newVal = trim((string) ($_POST[$k] ?? ''));
            $oldVal = Settings::set($k, $newVal !== '' ? $newVal : null, $userId);
            if ($oldVal !== $newVal) {
                $changed[] = $k;
            }
        }

        Session::flash('cs_msg', count($changed) > 0
            ? 'Company settings updated (' . count($changed) . ' fields changed).'
            : 'No changes detected.');

        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
            strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            $this->json(['ok' => true, 'changed' => $changed]);
        }

        header('Location: ' . url('/CompanySettings'));
        exit;
    }
}