<?php

function disableSchedule(int $scheduleId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("UPDATE schedules SET status = 'disabled' WHERE id = ?");
    $result = $stmt->execute([$scheduleId]);
    
    if ($result) {
        logActivity($_SESSION['user_id'] ?? 0, 'disable_schedule', "Programación deshabilitada ID: {$scheduleId}");
    }
    
    return $result;
}

function enableSchedule(int $scheduleId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("UPDATE schedules SET status = 'pending' WHERE id = ? AND status = 'disabled'");
    $result = $stmt->execute([$scheduleId]);
    
    if ($result) {
        logActivity($_SESSION['user_id'] ?? 0, 'enable_schedule', "Programación habilitada ID: {$scheduleId}");
    }
    
    return $result;
}

function cancelSchedule(int $scheduleId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("UPDATE schedules SET status = 'cancelled' WHERE id = ?");
    $result = $stmt->execute([$scheduleId]);
    
    if ($result) {
        logActivity($_SESSION['user_id'] ?? 0, 'cancel_schedule', "Programación cancelada ID: {$scheduleId}");
    }
    
    return $result;
}

function retrySchedule(int $scheduleId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("UPDATE schedules SET status = 'pending', error_message = NULL WHERE id = ? AND status = 'failed'");
    $result = $stmt->execute([$scheduleId]);
    
    if ($result) {
        logActivity($_SESSION['user_id'] ?? 0, 'retry_schedule', "Programación reintentada ID: {$scheduleId}");
    }
    
    return $result;
}

function deleteSchedule(int $scheduleId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT message_id FROM schedules WHERE id = ?");
    $stmt->execute([$scheduleId]);
    $schedule = $stmt->fetch();
    
    if ($schedule) {
        $stmt = $pdo->prepare("DELETE FROM schedules WHERE id = ?");
        $stmt->execute([$scheduleId]);
        
        $stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
        $stmt->execute([$schedule['message_id']]);
        
        logActivity($_SESSION['user_id'] ?? 0, 'delete_schedule', "Programación eliminada ID: {$scheduleId}");
        
        return true;
    }
    
    return false;
}

function handleScheduleAction(int $scheduleId, string $action): array
{
    $result = match ($action) {
        'disable' => disableSchedule($scheduleId),
        'enable' => enableSchedule($scheduleId),
        'cancel' => cancelSchedule($scheduleId),
        'retry' => retrySchedule($scheduleId),
        'delete' => deleteSchedule($scheduleId),
        default => false
    };

    return [
        'success' => $result,
        'action' => $action,
        'schedule_id' => $scheduleId
    ];
}
