<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\DB;

class AuthController extends Controller
{
    public function showLogin(): void
    {
        $this->view('auth/login');
    }

    public function login(): void
    {
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        $stmt = DB::pdo()->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        if ($user && password_verify($password, $user['password'])) {
            try {
                $log = DB::pdo()->prepare("INSERT INTO login_logs (user_id, email, success, ip, created_at) VALUES (?, ?, 1, ?, ?)");
                $log->execute([(int)$user['id'], $email, $_SERVER['REMOTE_ADDR'] ?? '', date('Y-m-d H:i:s')]);
            } catch (\Throwable $e) {
            }
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['tenant_id'] = $user['tenant_id'];
            $_SESSION['role'] = $user['role'] ?? 'empresa';
            header('Location: /dashboard');
            return;
        }
        try {
            $log = DB::pdo()->prepare("INSERT INTO login_logs (user_id, email, success, ip, created_at) VALUES (?, ?, 0, ?, ?)");
            $log->execute([null, $email, $_SERVER['REMOTE_ADDR'] ?? '', date('Y-m-d H:i:s')]);
        } catch (\Throwable $e) {
        }
        header('Location: /login');
    }

    public function showRegister(): void
    {
        $this->view('auth/register');
    }

    public function register(): void
    {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $tenantName = trim($_POST['tenant_name'] ?? '');
        $cnpj = preg_replace('/\D+/', '', $_POST['cnpj'] ?? '');
        $now = date('Y-m-d H:i:s');
        $checkTenant = DB::pdo()->prepare("SELECT id FROM tenants WHERE cnpj = ?");
        $checkTenant->execute([$cnpj]);
        $rowTenant = $checkTenant->fetch();
        if ($rowTenant) {
            $tenantId = (int)$rowTenant['id'];
        } else {
            $stmt = DB::pdo()->prepare("INSERT INTO tenants (name, cnpj, status, created_at, updated_at) VALUES (?, ?, 'ativo', ?, ?)");
            $stmt->execute([$tenantName, $cnpj, $now, $now]);
            $tenantId = (int)DB::pdo()->lastInsertId();
        }
        $checkUser = DB::pdo()->prepare("SELECT id FROM users WHERE email = ?");
        $checkUser->execute([$email]);
        if ($checkUser->fetch()) {
            header('Location: /login');
            return;
        }
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = DB::pdo()->prepare("INSERT INTO users (tenant_id, name, email, password, role, created_at, updated_at) VALUES (?, ?, ?, ?, 'admin', ?, ?)");
        $stmt->execute([$tenantId, $name, $email, $hash, $now, $now]);
        header('Location: /login');
    }

    public function logout(): void
    {
        session_destroy();
        header('Location: /login');
    }

    public function showProfile(): void
    {
        $userId = $_SESSION['user_id'] ?? null;
        if (!$userId) {
            header('Location: /login');
            return;
        }
        $stmt = DB::pdo()->prepare("SELECT name, email FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        $this->view('auth/profile', ['user' => $user]);
    }

    public function profileSave(): void
    {
        $userId = $_SESSION['user_id'] ?? null;
        if (!$userId) {
            header('Location: /login');
            return;
        }
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        if ($email === '') {
            header('Location: /perfil?err=email');
            return;
        }
        $check = DB::pdo()->prepare("SELECT id FROM users WHERE email = ? AND id <> ?");
        $check->execute([$email, $userId]);
        if ($check->fetch()) {
            header('Location: /perfil?err=email');
            return;
        }
        $stmt = DB::pdo()->prepare("UPDATE users SET name = ?, email = ?, updated_at = ? WHERE id = ?");
        $stmt->execute([$name, $email, date('Y-m-d H:i:s'), $userId]);
        header('Location: /perfil?ok=1');
    }

    public function profilePassword(): void
    {
        $userId = $_SESSION['user_id'] ?? null;
        if (!$userId) {
            header('Location: /login');
            return;
        }
        $current = $_POST['current_password'] ?? '';
        $new = $_POST['new_password'] ?? '';
        if ($new === '') {
            header('Location: /perfil?err=senha');
            return;
        }
        $stmt = DB::pdo()->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $row = $stmt->fetch();
        if (!$row || !password_verify($current, $row['password'])) {
            header('Location: /perfil?err=senha');
            return;
        }
        $hash = password_hash($new, PASSWORD_DEFAULT);
        $up = DB::pdo()->prepare("UPDATE users SET password = ?, updated_at = ? WHERE id = ?");
        $up->execute([$hash, date('Y-m-d H:i:s'), $userId]);
        header('Location: /perfil?ok=2');
    }
}
