<?php

/**
 * User Controller
 * Handles user management (CRUD operations)
 */
class UserController {
    
    private $authController;
    private $userModel;
    
    public function __construct() {
        $this->authController = new AuthController();
        $this->authController->requireAuth();
        
        $this->userModel = new User();
    }
    
    /**
     * List all users
     */
    public function index() {
        $pageTitle = 'Users';
        
        // Get all users
        $users = $this->userModel->getAll();
        
        require_once APP_PATH . '/views/admin/users/index.php';
    }
    
    /**
     * Show create user form
     */
    public function create() {
        $pageTitle = 'Add New User';
        
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->store();
            return;
        }
        
        require_once APP_PATH . '/views/admin/users/create.php';
    }
    
    /**
     * Store new user
     */
    private function store() {
        // Get and sanitize input
        $username = sanitize($_POST['username'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        $userType = sanitize($_POST['user_type'] ?? 'user');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        // Validation
        $errors = [];
        
        if (empty($username)) {
            $errors[] = 'Username is required';
        }
        
        if (empty($email)) {
            $errors[] = 'Email is required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Invalid email format';
        }
        
        if (empty($password)) {
            $errors[] = 'Password is required';
        } elseif (strlen($password) < PASSWORD_MIN_LENGTH) {
            $errors[] = 'Password must be at least ' . PASSWORD_MIN_LENGTH . ' characters';
        }
        
        if ($password !== $confirmPassword) {
            $errors[] = 'Passwords do not match';
        }
        
        // Validate user type
        if (!in_array($userType, ['admin', 'user'])) {
            $errors[] = 'Invalid user type';
        }
        
        // Check if username already exists
        if ($this->userModel->findByUsername($username)) {
            $errors[] = 'Username already exists';
        }
        
        // Check if email already exists
        if ($this->userModel->findByEmail($email)) {
            $errors[] = 'Email already exists';
        }
        
        if (!empty($errors)) {
            $pageTitle = 'Add New User';
            $errorMessage = implode('<br>', $errors);
            require_once APP_PATH . '/views/admin/users/create.php';
            return;
        }
        
        // Create user
        $userId = $this->userModel->create([
            'username' => $username,
            'email' => $email,
            'password' => $password,
            'user_type' => $userType,
            'is_active' => $isActive
        ]);
        
        if ($userId) {
            $_SESSION['success'] = 'User created successfully';
            redirect(BASE_URL . '/admin/users');
        } else {
            $pageTitle = 'Add New User';
            $errorMessage = 'Failed to create user';
            require_once APP_PATH . '/views/admin/users/create.php';
        }
    }
    
    /**
     * Show edit user form
     */
    public function edit($id) {
        $pageTitle = 'Edit User';
        
        // Get user
        $user = $this->userModel->findById($id);
        
        if (!$user) {
            redirect(BASE_URL . '/admin/users?error=' . urlencode('User not found'));
            return;
        }
        
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->update($id);
            return;
        }
        
        require_once APP_PATH . '/views/admin/users/edit.php';
    }
    
    /**
     * Update user
     */
    private function update($id) {
        // Get user
        $user = $this->userModel->findById($id);
        
        if (!$user) {
            redirect(BASE_URL . '/admin/users?error=' . urlencode('User not found'));
            return;
        }
        
        // Get and sanitize input
        $username = sanitize($_POST['username'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        $userType = sanitize($_POST['user_type'] ?? 'user');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        // Validation
        $errors = [];
        
        if (empty($username)) {
            $errors[] = 'Username is required';
        }
        
        if (empty($email)) {
            $errors[] = 'Email is required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Invalid email format';
        }
        
        // Validate user type
        if (!in_array($userType, ['admin', 'user'])) {
            $errors[] = 'Invalid user type';
        }
        
        // Check if username already exists (excluding current user)
        $existingUser = $this->userModel->findByUsername($username);
        if ($existingUser && $existingUser->id != $id) {
            $errors[] = 'Username already exists';
        }
        
        // Check if email already exists (excluding current user)
        $existingUser = $this->userModel->findByEmail($email);
        if ($existingUser && $existingUser->id != $id) {
            $errors[] = 'Email already exists';
        }
        
        // Validate password if provided
        if (!empty($password)) {
            if (strlen($password) < PASSWORD_MIN_LENGTH) {
                $errors[] = 'Password must be at least ' . PASSWORD_MIN_LENGTH . ' characters';
            }
            
            if ($password !== $confirmPassword) {
                $errors[] = 'Passwords do not match';
            }
        }
        
        if (!empty($errors)) {
            $pageTitle = 'Edit User';
            $errorMessage = implode('<br>', $errors);
            require_once APP_PATH . '/views/admin/users/edit.php';
            return;
        }
        
        // Prepare update data
        $updateData = [
            'username' => $username,
            'email' => $email,
            'user_type' => $userType,
            'is_active' => $isActive
        ];
        
        // Add password if provided
        if (!empty($password)) {
            $updateData['password'] = $password;
        }
        
        // Update user
        $result = $this->userModel->update($id, $updateData);
        
        if ($result) {
            $_SESSION['success'] = 'User updated successfully';
            redirect(BASE_URL . '/admin/users');
        } else {
            $pageTitle = 'Edit User';
            $errorMessage = 'Failed to update user';
            require_once APP_PATH . '/views/admin/users/edit.php';
        }
    }
    
    /**
     * Delete user
     */
    public function delete($id) {
        // Prevent deleting yourself
        if ($id == getCurrentUserId()) {
            $_SESSION['error'] = 'You cannot delete your own account';
            redirect(BASE_URL . '/admin/users');
            return;
        }
        
        // Delete user
        $result = $this->userModel->delete($id);
        
        if ($result) {
            $_SESSION['success'] = 'User deleted successfully';
            redirect(BASE_URL . '/admin/users');
        } else {
            $_SESSION['error'] = 'Failed to delete user';
            redirect(BASE_URL . '/admin/users');
        }
    }
}
