<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\User;

class UserController {
    public function index() {
        if (!Auth::check() || (Auth::user()['role'] !== 'admin' && Auth::user()['role'] !== 'staff')) {
            redirect('/login');
            exit;
        }

        $userModel = new User();
        $params = [
            'search' => $_GET['search'] ?? '',
        ];
        $users = $userModel->search($params);

        // Define available modules for permission selection
        $availableModules = [
            'dashboard' => ['label' => 'Dashboard', 'icon' => 'fa-gauge-high'],
            'leads' => ['label' => 'Lead Management', 'icon' => 'fa-users-viewfinder'],
            'students' => ['label' => 'Our Students', 'icon' => 'fa-user-graduate'],
            'admissions' => ['label' => 'Admissions', 'icon' => 'fa-graduation-cap'],
            'attendance' => ['label' => 'Attendance', 'icon' => 'fa-clipboard-user'],
            'teachers' => ['label' => 'Teachers', 'icon' => 'fa-chalkboard-user'],
            'courses' => ['label' => 'Courses', 'icon' => 'fa-book-open'],
            'batches' => ['label' => 'Batches', 'icon' => 'fa-users-rectangle'],
            'materials' => ['label' => 'Study Materials', 'icon' => 'fa-folder-open'],
            'categories' => ['label' => 'Course Categories', 'icon' => 'fa-layer-group'],
            'fees_head' => ['label' => 'Fees Head', 'icon' => 'fa-tags'],
            'fees_management' => ['label' => 'Fees Management', 'icon' => 'fa-hand-holding-dollar'],
            'expenses' => ['label' => 'Expenses', 'icon' => 'fa-receipt'],
            'expense_categories' => ['label' => 'Expense Categories', 'icon' => 'fa-folder-tree'],
            'certificates' => ['label' => 'Certificates', 'icon' => 'fa-certificate'],
            'users' => ['label' => 'Staff Management', 'icon' => 'fa-user-gear'],
            'settings' => ['label' => 'Institute Settings', 'icon' => 'fa-gear'],
        ];

        $title = 'Staff Management';
        require_once __DIR__ . '/../../views/admin/users.php';
    }

    public function save() {
        if (!Auth::check() || (Auth::user()['role'] !== 'admin' && Auth::user()['role'] !== 'staff')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $userModel = new User();
            
            // Password match check
            if (!empty($_POST['password']) && $_POST['password'] !== $_POST['confirm_password']) {
                $_SESSION['toast'] = ['message' => 'Passwords do not match.', 'type' => 'error'];
                redirect('/admin/users');
                exit;
            }

            $permissions = isset($_POST['permissions']) ? json_encode($_POST['permissions']) : null;

            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name'],
                'email' => $_POST['email'],
                'password' => $_POST['password'] ?? '',
                'role' => $_POST['role'] ?? 'staff',
                'permissions' => $permissions
            ];

            try {
                $userModel->save($data);
                $_SESSION['toast'] = ['message' => $data['id'] ? 'User updated!' : 'User created!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/users');
        exit;
    }

    public function delete() {
        if (!Auth::check() || (Auth::user()['role'] !== 'admin' && Auth::user()['role'] !== 'staff')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $userModel = new User();
            $userModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'User removed.', 'type' => 'info'];
        }
        redirect('/admin/users');
        exit;
    }
}
