<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\Settings;

class SettingsController extends Controller
{
    /**
     * Show settings form
     */
    public function index()
    {
        $this->requireAuth();
        $settings = new Settings();
        $data = $settings->all();
        $this->render('settings/index', [
            'pageTitle' => 'System Settings',
            'settings' => $data
        ]);
    }

    /**
     * Save settings (including logo upload)
     */
    public function save()
    {
        $this->requireAuth();
        $settings = new Settings();

        // -- Handle logo upload --
        $logoPath = null;
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../../public/uploads/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $file = $_FILES['logo'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
            if (!in_array($ext, $allowed)) {
                $_SESSION['error'] = 'Invalid logo file type. Allowed: jpg, png, gif, svg.';
                $this->redirect('/settings');
                return;
            }

            $filename = 'logo_' . time() . '.' . $ext;
            $destPath = $uploadDir . $filename;
            if (move_uploaded_file($file['tmp_name'], $destPath)) {
                $logoPath = 'uploads/' . $filename; // Relative to public/
            }
        }

        // Collect all settings from the form
        $data = [
            'company_name'        => $_POST['company_name'] ?? '',
            'base_currency'       => $_POST['base_currency'] ?? 'KES',
            'smtp_host'           => $_POST['smtp_host'] ?? '',
            'smtp_port'           => $_POST['smtp_port'] ?? '',
            'smtp_username'       => $_POST['smtp_username'] ?? '',
            'smtp_password'       => $_POST['smtp_password'] ?? '',
            'at_api_key'          => $_POST['at_api_key'] ?? '',
            'at_sender_id'        => $_POST['at_sender_id'] ?? '',
            'exchange_rate_api_key' => $_POST['exchange_rate_api_key'] ?? '',
        ];

        // If a new logo was uploaded, add/update the 'logo' key
        if ($logoPath) {
            $data['logo'] = $logoPath;
        }

        // Persist all settings
        if ($settings->save($data)) {
            $_SESSION['success'] = 'Settings saved successfully.';
        } else {
            $_SESSION['error'] = 'Failed to save settings.';
        }
        $this->redirect('/settings');
    }
}