<?php
ob_start();
header('Content-Type: application/json');
require_once '../core/api.php';

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

try {
    if (empty($data['first_name']) || empty($data['email'])) {
        throw new Exception('Nombre y Email son obligatorios');
    }

    $access_code = str_pad((string)random_int(0, 99999), 5, '0', STR_PAD_LEFT);
    $first_name = trim($data['first_name']);
    $last_name = trim($data['last_name'] ?? '');
    $email = trim($data['email']);
    $phone = trim($data['phone'] ?? '');
    
    // Capturar datos avanzados en creación
    $hourly_rate = isset($data['hourly_rate']) ? (float)$data['hourly_rate'] : 0.00;
    $schedule_json = isset($data['schedule']) ? json_encode($data['schedule']) : null;
    $is_employee_month = isset($data['is_employee_month']) ? (int)$data['is_employee_month'] : 0;

    // USANDO 'active' como el valor del ENUM en la BD
    $stmt = $pdo->prepare("INSERT INTO staff (first_name, last_name, email, phone, access_code, hourly_rate, schedule_config, is_employee_of_month, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active')");
    
    $stmt->execute([
        $first_name, $last_name, $email, $phone, 
        $access_code, $hourly_rate, $schedule_json, $is_employee_month
    ]);

    // Obtener ID del nuevo empleado
    $newId = $pdo->lastInsertId();

    // Gestionar Días Bloqueados (si se enviaron en la creación)
    if (isset($data['blocked_days']) && is_array($data['blocked_days'])) {
        $stmtBlock = $pdo->prepare("INSERT INTO staff_blocked_days (staff_id, blocked_date, reason) VALUES (?, ?, ?)");
        foreach ($data['blocked_days'] as $day) {
            if (!empty($day['date'])) {
                $reason = !empty($day['reason']) ? $day['reason'] : 'Permiso';
                $stmtBlock->execute([$newId, $day['date'], $reason]);
            }
        }
    }

    echo json_encode(['success' => true, 'message' => 'Empleado creado con éxito']);

} catch (PDOException $e) {
    if ($e->errorInfo[1] == 1062) {
        echo json_encode(['success' => false, 'message' => 'El email ya está registrado']);
    } else {
        error_log($e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Error al guardar en base de datos']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
?>