<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\User;

class UserController extends Controller {
    
    protected $userModel;
    
    public function __construct() {
        parent::__construct();
        $this->userModel = new User();
        
        // Debug: Log session info
        error_log("UserController constructor - Session: " . print_r($_SESSION, true));
        
        // Check if user is logged in
        if (!$this->isAuthenticated()) {
            error_log("UserController: Not authenticated, redirecting to login");
            $this->redirect('/login');
            return;
        }
        
        // Check for role in either 'role' or 'user_role' session keys
        $userRole = $_SESSION['user_role'] ?? $_SESSION['role'] ?? null;
        error_log("UserController: User role = " . ($userRole ?? 'NULL'));
        
        if ($userRole !== 'SuperAdmin') {
            error_log("UserController: Access denied for role: " . ($userRole ?? 'none'));
            
            http_response_code(403);
            $this->render('errors/403', ['message' => 'Access denied. SuperAdmin only.']);
            exit;
        }
        
        error_log("UserController: Access granted for SuperAdmin");
    }
    
    /**
     * List all users
     */
    public function index() {
        $users = $this->userModel->all('full_name', 'ASC');
        
        $this->render('admin/users/index', [
            'title' => 'User Management',
            'users' => $users,
            'csrf_token' => $this->csrf_token()
        ]);
    }
    
    /**
     * Show create user form
     */
    public function create() {
        $this->render('admin/users/create', [
            'title' => 'Create User',
            'csrf_token' => $this->csrf_token()
        ]);
    }
    
    /**
     * Store new user
     */
    public function store() {
        // Verify CSRF
        if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
            $_SESSION['error'] = 'Invalid CSRF token';
            $this->redirect('/users/create');
            return;
        }
        
        $data = $_POST;
        
        // Validate
        $errors = [];
        if (empty($data['username'])) $errors[] = 'Username is required';
        if (empty($data['email'])) $errors[] = 'Email is required';
        if (empty($data['password'])) $errors[] = 'Password is required';
        if (($data['password'] ?? '') !== ($data['confirm_password'] ?? '')) $errors[] = 'Passwords do not match';
        if (strlen($data['password'] ?? '') < 8) $errors[] = 'Password must be at least 8 characters';
        if (!filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email format';
        
        // Check if username exists
        if ($this->userModel->findByUsername($data['username'])) {
            $errors[] = 'Username already exists';
        }
        
        // Check if email exists
        if ($this->userModel->findByEmail($data['email'])) {
            $errors[] = 'Email already exists';
        }
        
        if (!empty($errors)) {
            $_SESSION['errors'] = $errors;
            $_SESSION['form_data'] = $data;
            $this->redirect('/users/create');
            return;
        }
        
        // Create user
        $user = $this->userModel->createUser($data);
        
        if ($user) {
            $_SESSION['success'] = 'User created successfully';
        } else {
            $_SESSION['error'] = 'Failed to create user';
        }
        
        $this->redirect('/users');
    }
    
    /**
     * Edit user
     */
    public function edit($params) {
        $id = $params['id'] ?? 0;
        $user = $this->userModel->find($id);
        
        if (!$user) {
            $_SESSION['error'] = 'User not found';
            $this->redirect('/users');
            return;
        }
        
        $this->render('admin/users/edit', [
            'title' => 'Edit User',
            'user' => $user,
            'csrf_token' => $this->csrf_token()
        ]);
    }
    
    /**
     * Update user
     */
    public function update($params) {
        // Verify CSRF
        if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
            $_SESSION['error'] = 'Invalid CSRF token';
            $this->redirect('/users');
            return;
        }
        
        $id = $params['id'] ?? 0;
        $data = $_POST;
        
        $user = $this->userModel->find($id);
        if (!$user) {
            $_SESSION['error'] = 'User not found';
            $this->redirect('/users');
            return;
        }
        
        // Don't allow changing own role to non-SuperAdmin
        if ($id == $_SESSION['user_id'] && isset($data['role']) && $data['role'] !== 'SuperAdmin') {
            $_SESSION['error'] = 'You cannot change your own role from SuperAdmin';
            $this->redirect('/users/' . $id . '/edit');
            return;
        }
        
        // Validate email if changed
        if (!empty($data['email']) && $data['email'] !== $user['email']) {
            if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
                $_SESSION['error'] = 'Invalid email format';
                $this->redirect('/users/' . $id . '/edit');
                return;
            }
            
            $existing = $this->userModel->findByEmail($data['email']);
            if ($existing && $existing['id'] != $id) {
                $_SESSION['error'] = 'Email already in use';
                $this->redirect('/users/' . $id . '/edit');
                return;
            }
        }
        
        // Update user
        $updated = $this->userModel->updateUser($id, $data);
        
        if ($updated) {
            $_SESSION['success'] = 'User updated successfully';
        } else {
            $_SESSION['error'] = 'Failed to update user';
        }
        
        $this->redirect('/users');
    }
    
    /**
     * Delete user
     */
    public function delete($params) {
        // Verify CSRF
        if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
            $_SESSION['error'] = 'Invalid CSRF token';
            $this->redirect('/users');
            return;
        }
        
        $id = $params['id'] ?? 0;
        
        // Don't allow deleting own account
        if ($id == $_SESSION['user_id']) {
            $_SESSION['error'] = 'You cannot delete your own account';
            $this->redirect('/users');
            return;
        }
        
        $user = $this->userModel->find($id);
        if (!$user) {
            $_SESSION['error'] = 'User not found';
            $this->redirect('/users');
            return;
        }
        
        $deleted = $this->userModel->delete($id);
        
        if ($deleted) {
            $_SESSION['success'] = 'User deleted successfully';
        } else {
            $_SESSION['error'] = 'Failed to delete user';
        }
        
        $this->redirect('/users');
    }
}