<?php
/**
 * Admin User Setup - Create additional admin users after installation
 * 
 * This script allows creating additional admin users after the initial installation.
 * It requires an existing super_admin user to be logged in.
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Include required files
require_once '../lib/Response.php';
require_once '../lib/Auth.php';

$response = new Response();
$auth = new Auth();

// Get request data
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $_GET['action'] ?? '';

// Check if user is authenticated and is super_admin
function verifySuperAdmin() {
    global $auth, $response;
    
    $user_data = $auth->authenticate();
    if (!$user_data) {
        $response->unauthorized('Authentication required');
        exit;
    }
    
    if ($user_data['role'] !== 'super_admin') {
        $response->forbidden('Super admin access required');
        exit;
    }
    
    return $user_data;
}

// Create new admin user
function createAdminUser($userData) {
    global $response;
    
    $required = ['name', 'email', 'password', 'role'];
    $missing = array_diff($required, array_keys($userData));
    
    if (!empty($missing)) {
        $response->validationError(['Missing required fields: ' . implode(', ', $missing)]);
        exit;
    }
    
    // Validate role
    $allowed_roles = ['admin', 'employee'];
    if (!in_array($userData['role'], $allowed_roles)) {
        $response->validationError(['Invalid role. Allowed roles: ' . implode(', ', $allowed_roles)]);
        exit;
    }
    
    // Validate email
    if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
        $response->validationError(['Invalid email format']);
        exit;
    }
    
    try {
        $pdo = getDBConnection();
        
        // Check if user already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$userData['email']]);
        
        if ($stmt->fetch()) {
            $response->error('User with this email already exists');
            exit;
        }
        
        // Hash password
        $hashedPassword = password_hash($userData['password'], PASSWORD_DEFAULT);
        
        // Create user
        $stmt = $pdo->prepare("
            INSERT INTO users (name, email, password, phone, role, status, created_by) 
            VALUES (?, ?, ?, ?, ?, 'active', ?)
        ");
        $stmt->execute([
            $userData['name'],
            $userData['email'],
            $hashedPassword,
            $userData['phone'] ?? '',
            $userData['role'],
            $userData['created_by']
        ]);
        
        $userId = $pdo->lastInsertId();
        
        // Set default permissions based on role
        if ($userData['role'] === 'employee') {
            setDefaultEmployeePermissions($userId);
        }
        
        return [
            'success' => true,
            'message' => 'User created successfully',
            'user_id' => $userId
        ];
        
    } catch (PDOException $e) {
        return [
            'success' => false,
            'message' => 'Failed to create user: ' . $e->getMessage()
        ];
    }
}

// Set default permissions for employee role
function setDefaultEmployeePermissions($userId) {
    try {
        $pdo = getDBConnection();
        
        $defaultPermissions = [
            ['dashboard', true, false, false, false],
            ['products', true, true, true, false],
            ['orders', true, true, true, false],
            ['appointments', true, true, true, false],
            ['payments', true, false, false, false],
            ['cars', true, false, false, false],
            ['sms', true, false, false, false]
        ];
        
        $stmt = $pdo->prepare("
            INSERT INTO user_permissions (user_id, module, can_view, can_create, can_edit, can_delete) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        foreach ($defaultPermissions as $permission) {
            $stmt->execute([$userId, $permission[0], $permission[1], $permission[2], $permission[3], $permission[4]]);
        }
        
        return true;
    } catch (PDOException $e) {
        // Log error but don't fail user creation
        error_log("Failed to set default permissions: " . $e->getMessage());
        return false;
    }
}

// Get list of admin users
function getAdminUsers() {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("
            SELECT id, name, email, phone, role, status, last_login, created_at 
            FROM users 
            WHERE role IN ('super_admin', 'admin', 'employee')
            ORDER BY role, name
        ");
        $stmt->execute();
        
        $users = $stmt->fetchAll();
        
        // Get permissions for each user
        foreach ($users as &$user) {
            $user['permissions'] = getUserPermissions($user['id']);
        }
        
        return [
            'success' => true,
            'users' => $users
        ];
        
    } catch (PDOException $e) {
        return [
            'success' => false,
            'message' => 'Failed to fetch users: ' . $e->getMessage()
        ];
    }
}

// Get user permissions
function getUserPermissions($userId) {
    try {
        $pdo = getDBConnection();
        
        $stmt = $pdo->prepare("
            SELECT module, can_view, can_create, can_edit, can_delete 
            FROM user_permissions 
            WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

// Update user permissions
function updateUserPermissions($userId, $permissions) {
    try {
        $pdo = getDBConnection();
        
        // Delete existing permissions
        $stmt = $pdo->prepare("DELETE FROM user_permissions WHERE user_id = ?");
        $stmt->execute([$userId]);
        
        // Insert new permissions
        $stmt = $pdo->prepare("
            INSERT INTO user_permissions (user_id, module, can_view, can_create, can_edit, can_delete) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        foreach ($permissions as $permission) {
            $stmt->execute([
                $userId,
                $permission['module'],
                $permission['can_view'] ? 1 : 0,
                $permission['can_create'] ? 1 : 0,
                $permission['can_edit'] ? 1 : 0,
                $permission['can_delete'] ? 1 : 0
            ]);
        }
        
        return [
            'success' => true,
            'message' => 'Permissions updated successfully'
        ];
        
    } catch (PDOException $e) {
        return [
            'success' => false,
            'message' => 'Failed to update permissions: ' . $e->getMessage()
        ];
    }
}

// Handle requests
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        verifySuperAdmin();
        
        if ($action === 'list') {
            $result = getAdminUsers();
            if ($result['success']) {
                $response->success($result);
            } else {
                $response->error($result['message']);
            }
        } else {
            $response->error('Invalid action');
        }
        break;
        
    case 'POST':
        $currentUser = verifySuperAdmin();
        
        switch ($action) {
            case 'create':
                $input['created_by'] = $currentUser['user_id'];
                $result = createAdminUser($input);
                
                if ($result['success']) {
                    $response->success($result);
                } else {
                    $response->error($result['message']);
                }
                break;
                
            case 'update-permissions':
                $required = ['user_id', 'permissions'];
                $missing = array_diff($required, array_keys($input));
                
                if (!empty($missing)) {
                    $response->validationError(['Missing required fields: ' . implode(', ', $missing)]);
                    break;
                }
                
                $result = updateUserPermissions($input['user_id'], $input['permissions']);
                
                if ($result['success']) {
                    $response->success($result);
                } else {
                    $response->error($result['message']);
                }
                break;
                
            default:
                $response->error('Invalid action');
                break;
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}
?>