<?php
class UsersController extends Controller {


    public function index() {
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    $userId = $_SESSION['user_id'];
    $role = $_SESSION['user_role'];

    $userModel = $this->model('User');

    $limit = 10;
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $offset = ($page - 1) * $limit;

    $users = $userModel->getUsersPaginated($limit, $offset);
    $totalUsers = $userModel->countUsers($userId, $role);
    $totalPages = ceil($totalUsers / $limit);

    $this->view('users/index', [
        'users' => $users,
        'role' => $role,
        'currentPage' => $page,
        'totalPages' => $totalPages
    ]);
}

    public function add() {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'name' => trim($_POST['name']),
                'email' => trim($_POST['email']),
                'role' => trim($_POST['role']),
                'password' => trim($_POST['password'])
                
            ];


            $userModel = $this->model('User');
            if ($userModel->addUser($data)) {
                header("Location: " . BASE_URL . "/users");
                exit;
            } else {
                $this->view('users/add', ['error' => 'Failed to add user', 'data' => $data]);
                return;
            }
        }

        $this->view('users/add');
    }

    public function edit($id = null) {
        session_start();
        if (!isset($_SESSION['user_id']) || !$id) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $userModel = $this->model('User');
        $user = $userModel->getUserById($id);

        if (!$user) {
            header("Location: " . BASE_URL . "/users");
            exit;
        }

        // Check ownership for non-admins
        if ($_SESSION['user_role'] !== 'admin' && $user['user_id'] != $_SESSION['user_id']) {
            header("Location: " . BASE_URL . "/users");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'name' => trim($_POST['name']),
                'email' => trim($_POST['email']),
                'role' => trim($_POST['role'])
            ];

            if ($userModel->updateUser($id, $data)) {
                header("Location: " . BASE_URL . "/users");
                exit;
            } else {
                $this->view('users/edit', ['error' => 'Failed to update user', 'user' => $user]);
                return;
            }
        }

        $this->view('users/edit', ['user' => $user]);
    }

    public function delete($id = null) {
        session_start();
        if (!isset($_SESSION['user_id']) || !$id) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $userModel = $this->model('User');
        $user = $userModel->getUserById($id);

        if (!$user) {
            header("Location: " . BASE_URL . "/users");
            exit;
        }

        // Check ownership for non-admins
        if ($_SESSION['user_role'] !== 'admin' && $user['user_id'] != $_SESSION['user_id']) {
            header("Location: " . BASE_URL . "/users");
            exit;
        }

        if ($userModel->deleteUser($id)) {
            header("Location: " . BASE_URL . "/users");
            exit;
        } else {
            echo "Failed to delete user.";
        }
    }
    
    

}
