<?php

namespace App\Controllers;

use App\Config\Database;
use App\Utils\View;

class AdminProfileController
{
    public function index()
    {
        if (!isset($_SESSION['user_id'])) {
            View::redirect('/login');
            return;
        }

        $userId = $_SESSION['user_id'];
        $conn = Database::getInstance()->getConnection();

        $stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = :id");
        $stmt->execute(['id' => $userId]);
        $user = $stmt->fetch();

        if (!$user) {
            View::redirect('/logout');
            return;
        }

        View::render('layouts.admin', [
            'title' => 'Meu Perfil',
            'content' => __DIR__ . '/../../resources/views/admin/profile.php',
            'user' => $user
        ]);
    }

    public function update()
    {
        if (!isset($_SESSION['user_id'])) {
            View::redirect('/login');
            return;
        }

        $userId = $_SESSION['user_id'];
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';

        if (empty($name) || empty($email)) {
            $_SESSION['flash_error'] = "Nome e Email são obrigatórios.";
            View::redirect('/admin/profile');
            return;
        }

        $conn = Database::getInstance()->getConnection();

        // Check if email is taken by another user
        $stmtCheck = $conn->prepare("SELECT id FROM users WHERE email = :email AND id != :id");
        $stmtCheck->execute(['email' => $email, 'id' => $userId]);
        if ($stmtCheck->fetch()) {
            $_SESSION['flash_error'] = "Este email já está em uso.";
            View::redirect('/admin/profile');
            return;
        }

        // Verify user still exists
        $stmtUser = $conn->prepare("SELECT id FROM users WHERE id = :id");
        $stmtUser->execute(['id' => $userId]);
        if (!$stmtUser->fetch()) {
            View::redirect('/logout');
            return;
        }

        // Verify user still exists
        $stmtUser = $conn->prepare("SELECT id FROM users WHERE id = :id");
        $stmtUser->execute(['id' => $userId]);
        if (!$stmtUser->fetch()) {
            View::redirect('/logout');
            return;
        }

        try {
            $stmt = $conn->prepare("UPDATE users SET name = :name, email = :email WHERE id = :id");
            $stmt->execute([
                'name' => $name,
                'email' => $email,
                'id' => $userId
            ]);

            // Update session name if changed
            $_SESSION['user_name'] = $name;

            $_SESSION['flash_success'] = "Perfil atualizado com sucesso!";
        } catch (\Exception $e) {
            $_SESSION['flash_error'] = "Erro ao atualizar perfil: " . $e->getMessage();
        }

        View::redirect('/admin/profile');
    }

    public function updatePassword()
    {
        if (!isset($_SESSION['user_id'])) {
            View::redirect('/login');
            return;
        }

        $userId = $_SESSION['user_id'];
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
            $_SESSION['flash_error'] = "Todos os campos de senha são obrigatórios.";
            View::redirect('/admin/profile');
            return;
        }

        if ($newPassword !== $confirmPassword) {
            $_SESSION['flash_error'] = "A nova senha e a confirmação não coincidem.";
            View::redirect('/admin/profile');
            return;
        }

        // Password Policy Validation (8 chars, 1 upper, 1 special)
        if (strlen($newPassword) < 8 || !preg_match('/[A-Z]/', $newPassword) || !preg_match('/[\W]/', $newPassword)) {
            $_SESSION['flash_error'] = "A nova senha deve ter pelo menos 8 caracteres, uma letra maiúscula e um caractere especial.";
            View::redirect('/admin/profile');
            return;
        }

        $conn = Database::getInstance()->getConnection();

        // Verify current password
        $stmt = $conn->prepare("SELECT password FROM users WHERE id = :id");
        $stmt->execute(['id' => $userId]);
        $user = $stmt->fetch();

        if (!$user) {
            View::redirect('/logout');
            return;
        }

        if (!password_verify($currentPassword, $user['password'])) {
            $_SESSION['flash_error'] = "Senha atual incorreta.";
            View::redirect('/admin/profile');
            return;
        }

        try {
            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmtUpdate = $conn->prepare("UPDATE users SET password = :password WHERE id = :id");
            $stmtUpdate->execute([
                'password' => $hashedPassword,
                'id' => $userId
            ]);

            $_SESSION['flash_success'] = "Senha alterada com sucesso!";
        } catch (\Exception $e) {
            $_SESSION['flash_error'] = "Erro ao alterar senha: " . $e->getMessage();
        }

        View::redirect('/admin/profile');
    }
}
