<?php

namespace App\Controllers;

use App\Services\Database;

class SettingsController extends BaseController
{
    public function index()
    {
        $this->requireAuth();
        $this->requireAdmin();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleSave();
            return;
        }

        // Obtener configuración actual
        $db = Database::getInstance();
        $settings = $db->fetchOne("SELECT * FROM app_settings WHERE id = 1");

        if (!$settings) {
            // Crear configuración por defecto si no existe
            $db->query("
                INSERT INTO app_settings (id, app_name, app_logo, created_at, updated_at) 
                VALUES (1, 'Sistema de Gestión de Proyectos', NULL, NOW(), NOW())
            ");
            $settings = $db->fetchOne("SELECT * FROM app_settings WHERE id = 1");
        }

        $this->render('settings/index', [
            'settings' => $settings
        ]);
    }

    private function handleSave()
    {
        header('Content-Type: application/json');
        
        try {
            $csrfToken = $_POST['csrf_token'] ?? '';
            
            if (!$this->validateCsrfToken($csrfToken)) {
                throw new \Exception('Token CSRF inválido');
            }

            $appName = trim($_POST['app_name'] ?? '');
            
            if (empty($appName)) {
                throw new \Exception('El nombre de la aplicación es requerido');
            }

            $db = Database::getInstance();
            $logoPath = null;

            // Procesar logo si se subió
            if (isset($_FILES['app_logo']) && $_FILES['app_logo']['error'] === UPLOAD_ERR_OK) {
                $logoPath = $this->uploadLogo($_FILES['app_logo']);
            }

            // Actualizar configuración
            if ($logoPath) {
                $db->update("
                    UPDATE app_settings 
                    SET app_name = ?, app_logo = ?, updated_at = NOW() 
                    WHERE id = 1
                ", [$appName, $logoPath]);
            } else {
                $db->update("
                    UPDATE app_settings 
                    SET app_name = ?, updated_at = NOW() 
                    WHERE id = 1
                ", [$appName]);
            }

            echo json_encode([
                'success' => true, 
                'message' => 'Configuración guardada correctamente',
                'logo_path' => $logoPath
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }

    private function uploadLogo($file): string
    {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
        $maxSize = 2 * 1024 * 1024; // 2MB

        if (!in_array($file['type'], $allowedTypes)) {
            throw new \Exception('Tipo de archivo no permitido. Solo JPG, PNG, GIF y SVG');
        }

        if ($file['size'] > $maxSize) {
            throw new \Exception('El archivo es muy grande. Máximo 2MB');
        }

        $uploadDir = __DIR__ . '/../../public/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'logo_' . time() . '.' . $extension;
        $filepath = $uploadDir . $filename;

        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            throw new \Exception('Error al subir el archivo');
        }

        return '/uploads/' . $filename;
    }
}
