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

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

try {
    // CASO 1: Actualizar Notificación Global
    if ($action === 'update_notification') {
        $msg = $input['message'] ?? '';
        // Asumiendo que staff_notifications tiene una columna 'message' y que la ID 1 es la global
        $pdo->prepare("UPDATE staff_notifications SET message = ?, updated_at = NOW() WHERE id = 1")->execute([$msg]);
        echo json_encode(['success' => true]);
        exit;
    }

    // CASO 2: Regenerar Código de Acceso
    if ($action === 'regenerate_code') {
        $id = $input['id'] ?? 0;
        $newCode = str_pad((string)random_int(0, 99999), 5, '0', STR_PAD_LEFT);
        $pdo->prepare("UPDATE staff SET access_code = ? WHERE id = ?")->execute([$newCode, $id]);
        echo json_encode(['success' => true, 'new_code' => $newCode]);
        exit;
    }

    // CASO 3: Actualizar Datos del Empleado
    if (empty($input['id'])) throw new Exception("ID requerido");
    $id = $input['id'];

    // Generar UID público para QR si no tiene
    $chk = $pdo->prepare("SELECT public_uid FROM staff WHERE id = ?");
    $chk->execute([$id]);
    if (empty($chk->fetchColumn())) {
        // Generar un UID público (por ejemplo, EMP-XXXX) y actualizar
        $uid = 'EMP-' . str_pad((string)random_int(1000, 9999), 4, '0', STR_PAD_LEFT);
        $pdo->prepare("UPDATE staff SET public_uid = ? WHERE id = ?")->execute([$uid, $id]);
    }

    // Actualizar campos
    $sql = "UPDATE staff SET 
            first_name = ?, last_name = ?, email = ?, phone = ?, 
            hourly_rate = ?, role = ?, is_employee_of_month = ?, schedule_config = ?
            WHERE id = ?";
    
    $scheduleJson = isset($input['schedule']) ? json_encode($input['schedule']) : '{}';
    $is_employee_month = isset($input['is_employee_month']) ? (int)$input['is_employee_of_month'] : 0; // Se corrige 'is_employee_month'

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $input['first_name'], 
        $input['last_name'], 
        $input['email'], 
        $input['phone'], 
        $input['hourly_rate'], 
        $input['role'], 
        $is_employee_month, // Uso la variable corregida
        $scheduleJson,
        $id
    ]);

    // Actualizar días bloqueados
    if (isset($input['blocked_days'])) {
        $pdo->prepare("DELETE FROM staff_blocked_days WHERE staff_id = ?")->execute([$id]);
        $stmtB = $pdo->prepare("INSERT INTO staff_blocked_days (staff_id, blocked_date, reason) VALUES (?, ?, ?)");
        foreach ($input['blocked_days'] as $day) {
            // Asegurando que los campos existan antes de ejecutar
            $date = $day['date'] ?? null;
            $reason = $day['reason'] ?? 'Permiso';
            if ($date) {
                $stmtB->execute([$id, $date, $reason]);
            }
        }
    }

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>