<?php

require_once '../app/Models/UserType.php';
require_once '../app/Models/PermissionScanner.php';

class UserTypeController
{
    private $userTypeModel;
    private $permissionScanner;
    
    public function __construct()
    {
        $this->userTypeModel = new UserType();
        $this->permissionScanner = new PermissionScanner();
        $this->checkAuth();
        $this->checkAdminAccess();
        
        // Auto-sync permissions only when accessing create/edit pages
        $currentAction = $_SERVER['REQUEST_URI'] ?? '';
        if (strpos($currentAction, '/create') !== false || strpos($currentAction, '/edit') !== false) {
            $this->permissionScanner->syncPermissionsToDatabase();
        }
    }
    
    private function checkAuth()
    {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /samanta_crm/login');
            exit;
        }
    }
    
    private function checkAdminAccess()
    {
        // For now, only admin role can manage user types
        // Later we can check specific permissions
        if ($_SESSION['user_role'] !== 'admin') {
            $_SESSION['error'] = 'Access denied. Admin privileges required.';
            header('Location: /samanta_crm/dashboard');
            exit;
        }
    }
    
    public function index()
    {
        $userTypes = $this->userTypeModel->getAll();
        $this->view('user_types/index', ['userTypes' => $userTypes]);
    }
    
    public function create()
    {
        $permissions = $this->permissionScanner->getPermissionsByCategory();
        $this->view('user_types/create', ['permissions' => $permissions]);
    }
    
    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/user-types/create');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'description' => $_POST['description'] ?? '',
            'color' => $_POST['color'] ?? '#007bff',
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'permissions' => $this->processPermissions($_POST['permissions'] ?? [])
        ];
        
        // Validation
        if (empty($data['name'])) {
            $_SESSION['error'] = 'User type name is required';
            header('Location: /samanta_crm/user-types/create');
            exit;
        }
        
        // Check if name already exists
        if ($this->userTypeModel->findByName($data['name'])) {
            $_SESSION['error'] = 'User type name already exists';
            header('Location: /samanta_crm/user-types/create');
            exit;
        }
        
        if ($this->userTypeModel->create($data)) {
            $_SESSION['success'] = 'User type created successfully';
        } else {
            $_SESSION['error'] = 'Failed to create user type';
        }
        
        header('Location: /samanta_crm/user-types');
        exit;
    }
    
    public function edit($id)
    {
        $userType = $this->userTypeModel->findById($id);
        
        if (!$userType) {
            $_SESSION['error'] = 'User type not found';
            header('Location: /samanta_crm/user-types');
            exit;
        }
        
        $permissions = $this->permissionScanner->getPermissionsByCategory();
        $this->view('user_types/edit', [
            'userType' => $userType,
            'permissions' => $permissions
        ]);
    }
    
    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/user-types');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'description' => $_POST['description'] ?? '',
            'color' => $_POST['color'] ?? '#007bff',
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'permissions' => $this->processPermissions($_POST['permissions'] ?? [])
        ];
        
        if (empty($data['name'])) {
            $_SESSION['error'] = 'User type name is required';
            header('Location: /samanta_crm/user-types/' . $id . '/edit');
            exit;
        }
        
        if ($this->userTypeModel->update($id, $data)) {
            $_SESSION['success'] = 'User type updated successfully';
        } else {
            $_SESSION['error'] = 'Failed to update user type';
        }
        
        header('Location: /samanta_crm/user-types');
        exit;
    }
    
    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/user-types');
            exit;
        }
        
        if ($this->userTypeModel->delete($id)) {
            $_SESSION['success'] = 'User type deleted successfully';
        } else {
            $_SESSION['error'] = 'Cannot delete user type. It may be in use by existing users.';
        }
        
        header('Location: /samanta_crm/user-types');
        exit;
    }
    
    private function processPermissions($permissions)
    {
        $processed = [];
        
        if (is_array($permissions)) {
            foreach ($permissions as $permission => $value) {
                // Store permissions as flat key-value pairs
                $processed[$permission] = true;
            }
        }
        
        return $processed;
    }
    
    private function view($view, $data = [])
    {
        extract($data);
        require_once "../app/Views/{$view}.php";
    }
}
