<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Models\User;

class AuthController extends Controller {
    public function showLogin(): void {
        if (Auth::check()) {
            Response::redirect('/dashboard');
        }
        $this->render('auth/login', [], 'layouts/auth');
    }

    public function login(): void {
        $email = trim(Request::post('email', ''));
        $password = Request::post('password', '');

        if (empty($email) || empty($password)) {
            if (Request::isAjax()) {
                Response::error('Please provide both email and password.');
            }
            Response::redirect('/login?error=empty_fields');
        }

        $user = User::findByEmail($email);
        if (!$user || !password_verify($password, $user['password_hash'])) {
            if (Request::isAjax()) {
                Response::error('Invalid email or password.');
            }
            Response::redirect('/login?error=invalid_credentials');
        }

        if ($user['status'] !== 'active') {
            if (Request::isAjax()) {
                Response::error('Your account is currently disabled. Please contact administrator.');
            }
            Response::redirect('/login?error=account_disabled');
        }

        Auth::login($user);

        if (Request::isAjax()) {
            Response::success(['redirect' => '/dashboard'], 'Login successful');
        }
        Response::redirect('/dashboard');
    }

    public function logout(): void {
        Auth::logout();
        Response::redirect('/login');
    }

    public function profile(): void {
        $user = User::find((int)Auth::id());
        $this->render('auth/profile', ['user' => $user]);
    }

    public function updateProfile(): void {
        $userId = (int)Auth::id();
        $name = trim(Request::post('name', ''));
        $email = trim(Request::post('email', ''));
        $password = Request::post('password', '');

        if (empty($name) || empty($email)) {
            Response::error('Name and Email are required.');
        }

        $updateData = ['name' => $name, 'email' => $email];

        if (!empty($password)) {
            if (strlen($password) < 6) {
                Response::error('Password must be at least 6 characters.');
            }
            $updateData['password_hash'] = password_hash($password, PASSWORD_BCRYPT);
        }

        User::update($userId, $updateData);
        $_SESSION['user']['name'] = $name;
        $_SESSION['user']['email'] = $email;

        Response::success(null, 'Profile updated successfully!');
    }
}
