<?php
/**
 * SalonPro X - Authentication Controller
 * Handles login, logout, password reset, and profile management
 */

namespace Modules\Authentication\Controllers;

use core\Controller;
use core\Request;
use core\Response;
use core\Auth;
use core\Session;
use core\Security;
use core\Validator;
use core\Database;
use core\View;

class AuthController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Display login form
     */
    public function loginForm(): void
    {
        if (Auth::check()) {
            $this->redirect(url('dashboard'));
            return;
        }
        View::render('Authentication/login', ['title' => 'Login'], 'auth');
    }

    /**
     * Process login request
     */
    public function login(): void
    {
        $data = $this->validate([
            'email' => 'required|email',
            'password' => 'required|min_length:6',
        ]);

        $remember = (bool)($this->request->post('remember'));

        if (Auth::attempt($data['email'], $data['password'], $remember)) {
            Auth::logActivity('login', 'User logged in: ' . $data['email']);
            Session::setAlert('success', 'Welcome back!');
            
            if ($this->request->isAjax()) {
                $this->success(['redirect' => url('dashboard')], 'Login successful');
            }
            $this->redirect(url('dashboard'));
        }

        if ($this->request->isAjax()) {
            $this->error('Invalid email or password.');
        }
        Session::setAlert('danger', 'Invalid email or password.');
        $this->redirect(url('login'));
    }

    /**
     * Logout
     */
    public function logout(): void
    {
        Auth::logout();
        Session::setAlert('info', 'You have been logged out.');
        $this->redirect(url('login'));
    }

    /**
     * Display forgot password form
     */
    public function forgotPasswordForm(): void
    {
        View::render('Authentication/forgot_password', ['title' => 'Forgot Password'], 'auth');
    }

    /**
     * Process forgot password request
     */
    public function forgotPassword(): void
    {
        $data = $this->validate([
            'email' => 'required|email',
        ]);

        $db = Database::getInstance();
        $user = $db->table('users')->where('email', $data['email'])->first();

        if ($user) {
            $token = Security::generateToken();
            $db->table('users')->where('id', $user->id)->update([
                'password_reset_token' => $token,
                'password_reset_expires' => date(DATE_TIME_FORMAT, strtotime('+1 hour')),
            ]);

            // In production, send email here
            $resetLink = url('reset-password/' . $token);
            logger("Password reset link for {$user->email}: {$resetLink}", 'info', 'auth');
        }

        Session::setAlert('info', 'If your email exists in our system, you will receive a password reset link.');
        $this->redirect(url('login'));
    }

    /**
     * Display reset password form
     */
    public function resetPasswordForm(string $token): void
    {
        $db = Database::getInstance();
        $user = $db->table('users')
            ->where('password_reset_token', $token)
            ->where('password_reset_expires', '>=', date(DATE_TIME_FORMAT))
            ->first();

        if (!$user) {
            Session::setAlert('danger', 'Invalid or expired reset token.');
            $this->redirect(url('login'));
        }

        View::render('Authentication/reset_password', [
            'title' => 'Reset Password',
            'token' => $token,
        ], 'auth');
    }

    /**
     * Process password reset
     */
    public function resetPassword(): void
    {
        $data = $this->validate([
            'token' => 'required',
            'password' => 'required|min_length:8',
            'password_confirm' => 'required|matches:password',
        ]);

        $db = Database::getInstance();
        $user = $db->table('users')
            ->where('password_reset_token', $data['token'])
            ->where('password_reset_expires', '>=', date(DATE_TIME_FORMAT))
            ->first();

        if (!$user) {
            Session::setAlert('danger', 'Invalid or expired reset token.');
            $this->redirect(url('login'));
        }

        $db->table('users')->where('id', $user->id)->update([
            'password' => Security::hashPassword($data['password']),
            'password_reset_token' => null,
            'password_reset_expires' => null,
            'password_changed_at' => date(DATE_TIME_FORMAT),
        ]);

        Session::setAlert('success', 'Password reset successful. Please login.');
        $this->redirect(url('login'));
    }

    /**
     * Display user profile
     */
    public function profile(): void
    {
        Auth::requireAuth();
        $db = Database::getInstance();
        $user = $db->table('users')
            ->select('users.*, roles.name as role_name, branches.name as branch_name')
            ->leftJoin('roles', 'users.role_id', '=', 'roles.id')
            ->leftJoin('branches', 'users.branch_id', '=', 'branches.id')
            ->where('users.id', Auth::id())
            ->first();

        $this->view('Authentication/profile', [
            'title' => 'My Profile',
            'profileUser' => $user,
            'breadcrumb' => ['Profile' => url('profile')],
        ]);
    }

    /**
     * Update user profile
     */
    public function updateProfile(): void
    {
        Auth::requireAuth();
        $data = $this->validate([
            'first_name' => 'required|max_length:50',
            'last_name' => 'required|max_length:50',
            'phone' => 'max_length:20',
        ]);

        $db = Database::getInstance();
        $updateData = [
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'phone' => $data['phone'] ?? '',
        ];

        if ($this->request->hasFile('avatar')) {
            $file = $this->request->file('avatar');
            $result = uploadFile($file, 'avatars');
            if ($result) {
                $updateData['avatar'] = $result;
            }
        }

        $db->table('users')->where('id', Auth::id())->update($updateData);
        Auth::logActivity('profile_update', 'User updated their profile');
        Session::setAlert('success', 'Profile updated successfully.');
        $this->back();
    }

    /**
     * Change user password
     */
    public function changePassword(): void
    {
        Auth::requireAuth();
        $data = $this->validate([
            'current_password' => 'required',
            'new_password' => 'required|min_length:8',
            'confirm_password' => 'required|matches:new_password',
        ]);

        $db = Database::getInstance();
        $user = $db->table('users')->find(Auth::id());

        if (!Security::verifyPassword($data['current_password'], $user->password)) {
            Session::setAlert('danger', 'Current password is incorrect.');
            $this->back();
            return;
        }

        $db->table('users')->where('id', Auth::id())->update([
            'password' => Security::hashPassword($data['new_password']),
            'password_changed_at' => date(DATE_TIME_FORMAT),
        ]);

        Auth::logActivity('password_change', 'User changed their password');
        Session::setAlert('success', 'Password changed successfully.');
        $this->back();
    }
}
