<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';
require_once __DIR__ . '/../../core/Logger.php';

$data = json_decode(file_get_contents('php://input'), true);

Validator::required($data, [
    'first_name',
    'last_name',
    'email',
    'password',
    'role_id'
]);

Validator::email($data['email']);
Validator::minLength($data['password'], PASSWORD_MIN_LENGTH, 'Password');

/**
 * Optional mobile validation
 */
$mobile = null;
if (!empty($data['mobile'])) {
    $mobile = trim($data['mobile']);
    Validator::minLength($mobile, 8, 'Mobile');
}

$db = Database::getInstance();

/**
 * Fetch logged-in employee role level
 */
$stmt = $db->prepare("
    SELECT r.level
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$currentUser = $stmt->fetch();

if (!$currentUser) {
    Response::error('Unauthorized', 401);
}

/**
 * Fetch target role level
 */
$stmt = $db->prepare("
    SELECT level FROM roles WHERE id = :role_id
");
$stmt->execute(['role_id' => $data['role_id']]);
$targetRole = $stmt->fetch();

if (!$targetRole) {
    Response::error('Invalid role selected', 422);
}

/**
 * Role hierarchy enforcement
 */
if ((int)$targetRole['level'] >= (int)$currentUser['level']) {
    Response::error('You cannot create an employee with equal or higher role', 403);
}

/**
 * Check email uniqueness
 */
$stmt = $db->prepare("
    SELECT id FROM employees WHERE email = :email
");
$stmt->execute(['email' => strtolower(trim($data['email']))]);

if ($stmt->fetch()) {
    Response::error('Email already exists', 409);
}

/**
 * Create employee
 */
$stmt = $db->prepare("
    INSERT INTO employees (
        role_id,
        first_name,
        last_name,
        email,
        mobile,
        password_hash,
        status,
        created_by,
        created_at
    ) VALUES (
        :role_id,
        :first_name,
        :last_name,
        :email,
        :mobile,
        :password_hash,
        'active',
        :created_by,
        NOW()
    )
");

$stmt->execute([
    'role_id'        => (int)$data['role_id'],
    'first_name'     => trim($data['first_name']),
    'last_name'      => trim($data['last_name']),
    'email'          => strtolower(trim($data['email'])),
    'mobile'         => $mobile,
    'password_hash' => password_hash($data['password'], PASSWORD_DEFAULT),
    'created_by'     => $_SESSION['employee_id']
]);

Logger::auth('Employee created', [
    'created_by' => $_SESSION['employee_id'],
    'email'      => $data['email']
]);

Response::success('Employee created successfully');
