<?php
/**
 * Admin Users and Permissions API Routes
 * 
 * Handles CRUD operations for users and their permissions.
 */

require_once '../lib/Auth.php';
require_once '../lib/Validation.php';

$auth = new Auth();
$validation = new Validation();
$response = new Response();
$db = getDB();

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

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // Require admin authentication
        $user_data = $auth->protectRoute('admin');
        
        if ($id) {
            // Get single user with permissions
            $stmt = $db->prepare("
                SELECT id, name, email, phone, role, status, created_at, created_by
                FROM users 
                WHERE id = ? AND role IN ('admin', 'employee')
            ");
            $stmt->execute([$id]);
            $user = $stmt->fetch();
            
            if (!$user) {
                $response->notFound('User not found');
            }
            
            // Get user permissions
            $permissions = $auth->getUserPermissions($id);
            
            $response->success([
                'user' => $user,
                'permissions' => $permissions
            ]);
            
        } else if ($action === 'permissions') {
            // Get all available modules for permissions
            $modules = [
                'dashboard' => 'Dashboard',
                'products' => 'Products',
                'orders' => 'Orders',
                'appointments' => 'Appointments',
                'payments' => 'Payments',
                'cars' => 'Cars',
                'sms' => 'SMS',
                'users' => 'Users'
            ];
            
            $response->success(['modules' => $modules]);
            
        } else {
            // Get all admin/employee users
            $page = max(1, intval($_GET['page'] ?? 1));
            $limit = min(50, max(1, intval($_GET['limit'] ?? 20)));
            $offset = ($page - 1) * $limit;
            
            $role = $_GET['role'] ?? null;
            $status = $_GET['status'] ?? 'active';
            $search = $_GET['search'] ?? null;
            
            $where_conditions = ["role IN ('admin', 'employee')"];
            $params = [];
            
            if ($role) {
                $where_conditions[] = "role = ?";
                $params[] = $role;
            }
            
            if ($status !== 'all') {
                $where_conditions[] = "status = ?";
                $params[] = $status;
            }
            
            if ($search) {
                $where_conditions[] = "(name LIKE ? OR email LIKE ?)";
                $search_term = "%$search%";
                $params[] = $search_term;
                $params[] = $search_term;
            }
            
            $where_clause = implode(' AND ', $where_conditions);
            
            // Get users
            $stmt = $db->prepare("
                SELECT id, name, email, phone, role, status, created_at, created_by
                FROM users 
                WHERE $where_clause
                ORDER BY created_at DESC
                LIMIT ? OFFSET ?
            ");
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);
            $users = $stmt->fetchAll();
            
            // Get total count
            $stmt = $db->prepare("SELECT COUNT(*) as total FROM users WHERE $where_clause");
            $count_params = array_slice($params, 0, count($params) - 2);
            $stmt->execute($count_params);
            $total = $stmt->fetch()['total'];
            
            $response->success([
                'users' => $users,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $total,
                    'pages' => ceil($total / $limit)
                ]
            ]);
        }
        break;
        
    case 'POST':
        // Require admin authentication
        $user_data = $auth->protectRoute('admin');
        
        if ($action === 'permissions') {
            // Update user permissions
            $user_id = $input['user_id'] ?? null;
            $permissions = $input['permissions'] ?? [];
            
            if (!$user_id) {
                $response->error('User ID is required', 400);
            }
            
            // Verify user exists and is employee
            $stmt = $db->prepare("SELECT id, role FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            
            if (!$user) {
                $response->notFound('User not found');
            }
            
            if ($user['role'] !== 'employee') {
                $response->error('Permissions can only be set for employees', 400);
            }
            
            try {
                $auth->updateUserPermissions($user_id, $permissions);
                $response->success(null, 'Permissions updated successfully');
                
            } catch (Exception $e) {
                $response->error('Failed to update permissions: ' . $e->getMessage(), 500);
            }
            
        } else {
            // Create new user (admin or employee)
            $required_fields = ['name', 'email', 'password', 'role'];
            $validation_result = $validation->validateRequired($input, $required_fields);
            
            if (!$validation_result['valid']) {
                $response->validationError($validation_result['errors']);
            }
            
            // Validate role
            if (!in_array($input['role'], ['admin', 'employee'])) {
                $response->error('Role must be either admin or employee', 400);
            }
            
            // Check if email already exists
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$input['email']]);
            
            if ($stmt->fetch()) {
                $response->error('Email already registered', 409);
            }
            
            try {
                // Hash password
                $hashed_password = password_hash($input['password'], PASSWORD_DEFAULT);
                
                // Insert new user
                $stmt = $db->prepare("
                    INSERT INTO users (name, email, password, phone, role, status, created_by)
                    VALUES (?, ?, ?, ?, ?, 'active', ?)
                ");
                $stmt->execute([
                    $validation->sanitize($input['name']),
                    $validation->sanitize($input['email']),
                    $hashed_password,
                    $input['phone'] ?? null,
                    $input['role'],
                    $user_data['user_id']
                ]);
                
                $user_id = $db->lastInsertId();
                
                // If employee, set default permissions
                if ($input['role'] === 'employee') {
                    $default_permissions = [
                        'dashboard' => ['view' => true, 'create' => false, 'edit' => false, 'delete' => false],
                        'products' => ['view' => true, 'create' => false, 'edit' => false, 'delete' => false],
                        'orders' => ['view' => true, 'create' => false, 'edit' => false, 'delete' => false],
                        'appointments' => ['view' => true, 'create' => false, 'edit' => false, 'delete' => false]
                    ];
                    $auth->updateUserPermissions($user_id, $default_permissions);
                }
                
                $response->success(['id' => $user_id], 'User created successfully');
                
            } catch (Exception $e) {
                $response->error('Failed to create user: ' . $e->getMessage(), 500);
            }
        }
        break;
        
    case 'PUT':
        // Require admin authentication
        $user_data = $auth->protectRoute('admin');
        
        if (!$id) {
            $response->error('User ID is required', 400);
        }
        
        // Update user
        $required_fields = ['name', 'email', 'role'];
        $validation_result = $validation->validateRequired($input, $required_fields);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        // Validate role
        if (!in_array($input['role'], ['admin', 'employee'])) {
            $response->error('Role must be either admin or employee', 400);
        }
        
        // Check if email already exists (excluding current user)
        $stmt = $db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$input['email'], $id]);
        
        if ($stmt->fetch()) {
            $response->error('Email already registered', 409);
        }
        
        try {
            $update_fields = [
                'name' => $validation->sanitize($input['name']),
                'email' => $validation->sanitize($input['email']),
                'phone' => $input['phone'] ?? null,
                'role' => $input['role'],
                'status' => $input['status'] ?? 'active'
            ];
            
            // Update password if provided
            if (!empty($input['password'])) {
                $update_fields['password'] = password_hash($input['password'], PASSWORD_DEFAULT);
            }
            
            $set_parts = [];
            $params = [];
            foreach ($update_fields as $field => $value) {
                $set_parts[] = "$field = ?";
                $params[] = $value;
            }
            $params[] = $id;
            
            $set_clause = implode(', ', $set_parts);
            
            $stmt = $db->prepare("UPDATE users SET $set_clause WHERE id = ?");
            $stmt->execute($params);
            
            $response->success(null, 'User updated successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to update user: ' . $e->getMessage(), 500);
        }
        break;
        
    case 'DELETE':
        // Require admin authentication
        $user_data = $auth->protectRoute('admin');
        
        if (!$id) {
            $response->error('User ID is required', 400);
        }
        
        // Prevent deleting self
        if ($id == $user_data['user_id']) {
            $response->error('Cannot delete your own account', 400);
        }
        
        try {
            // Soft delete user
            $stmt = $db->prepare("UPDATE users SET status = 'inactive' WHERE id = ?");
            $stmt->execute([$id]);
            
            $response->success(null, 'User deleted successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to delete user: ' . $e->getMessage(), 500);
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}
?>