<?php
/**
 * Authentication Controller
 * Handles login, logout, and token verification
 */

class AuthController {
    private $db;
    private $agentModel;

    public function __construct($db) {
        $this->db = $db;
        require_once __DIR__ . '/../models/Agent.php';
        $this->agentModel = new Agent($this->db);
    }

    /**
     * Handle login request
     */
    public function login() {
        $data = Auth::getRequestBody();

        // Validate and sanitize input using InputValidator
        $validationRules = [
            'username' => ['required' => true, 'type' => 'string', 'max_length' => 50],
            'password' => ['required' => true, 'type' => 'string', 'max_length' => 255]
        ];

        $validation = InputValidator::validateArray($data, $validationRules);

        if (!$validation['valid']) {
            Auth::sendError('Validation failed', 400, $validation['errors']);
        }

        $sanitizedData = $validation['data'];
        $username = $sanitizedData['username'];
        $password = $sanitizedData['password'];

        // Additional security checks
        if (InputValidator::checkSQLInjection($username) || InputValidator::checkSQLInjection($password)) {
            Auth::sendError('Invalid input detected', 400);
        }

        // Authenticate user
        $user = $this->agentModel->authenticate($username, $password);

        if ($user) {
            // Generate JWT token
            $token = Auth::generateToken($user);

            Auth::sendSuccess([
                'user' => $user,
                'token' => $token,
                'expires_in' => 24 * 60 * 60 // 24 hours in seconds
            ], 'Login successful');
        } else {
            Auth::sendError('Invalid username or password', 401);
        }
    }

    /**
     * Handle logout request
     */
    public function logout() {
        // In a stateless JWT system, logout is handled client-side
        // by removing the token from storage
        Auth::sendSuccess(null, 'Logout successful');
    }

    /**
     * Verify token and return current user info
     */
    public function verifyToken() {
        $user = Auth::requireAuth();

        Auth::sendSuccess([
            'user' => $user,
            'valid' => true
        ], 'Token is valid');
    }

    /**
     * Get current user profile
     */
    public function getProfile() {
        $user = Auth::requireAuth();

        $agentData = $this->agentModel->getById($user['id']);

        if ($agentData) {
            unset($agentData['password_hash']); // Remove sensitive data
            Auth::sendSuccess($agentData, 'Profile retrieved successfully');
        } else {
            Auth::sendError('User not found', 404);
        }
    }

    /**
     * Update user profile
     */
    public function updateProfile() {
        $user = Auth::requireAuth();
        $data = Auth::getRequestBody();

        // Only allow updating certain fields
        $allowedFields = ['full_name', 'email', 'phone'];
        $updateData = [];

        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $updateData[$field] = $data[$field];
            }
        }

        if (empty($updateData)) {
            Auth::sendError('No valid fields to update', 400);
        }

        // Validate email format if provided
        if (isset($updateData['email']) && !filter_var($updateData['email'], FILTER_VALIDATE_EMAIL)) {
            Auth::sendError('Invalid email format', 400);
        }

        $success = $this->agentModel->update($user['id'], $updateData);

        if ($success) {
            Auth::sendSuccess(null, 'Profile updated successfully');
        } else {
            Auth::sendError('Failed to update profile', 500);
        }
    }

    /**
     * Change password
     */
    public function changePassword() {
        $user = Auth::requireAuth();
        $data = Auth::getRequestBody();

        if (!isset($data['current_password']) || !isset($data['new_password'])) {
            Auth::sendError('Current password and new password are required', 400);
        }

        $currentPassword = $data['current_password'];
        $newPassword = $data['new_password'];

        if (strlen($newPassword) < 6) {
            Auth::sendError('New password must be at least 6 characters long', 400);
        }

        // Verify current password
        $agentData = $this->agentModel->getById($user['id']);

        if (!password_verify($currentPassword, $agentData['password_hash'])) {
            Auth::sendError('Current password is incorrect', 400);
        }

        // Update password
        $success = $this->agentModel->update($user['id'], ['password' => $newPassword]);

        if ($success) {
            Auth::sendSuccess(null, 'Password changed successfully');
        } else {
            Auth::sendError('Failed to change password', 500);
        }
    }
}
?>
