<?php

require_once __DIR__ . '/activity_logger.php';

function createMessage(array $data): int
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("
        INSERT INTO messages (user_id, content, created_at) 
        VALUES (?, ?, NOW())
    ");
    $stmt->execute([$data['user_id'], $data['content']]);
    
    return (int) $pdo->lastInsertId();
}

function createSchedule(array $data): int
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("
        INSERT INTO schedules (
            message_id, recipient_id, send_time, status,
            is_recurring, recurring_days, recurring_time, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([
        $data['message_id'],
        $data['recipient_id'],
        $data['send_time'],
        $data['status'] ?? 'pending',
        ($data['is_recurring'] ?? false) ? 1 : 0,
        $data['recurring_days'] ?? null,
        $data['recurring_time'] ?? null
    ]);
    
    return (int) $pdo->lastInsertId();
}

function handleCreateMessage(array $postData): array
{
    $required = ['content', 'recipient_id', 'send_type'];
    
    foreach ($required as $field) {
        if (empty($postData[$field])) {
            return ['success' => false, 'error' => "Falta el campo: {$field}"];
        }
    }

    $userId = $_SESSION['user_id'] ?? 0;
    
    $messageId = createMessage([
        'user_id' => $userId,
        'content' => $postData['content']
    ]);

    $sendTime = match ($postData['send_type']) {
        'now' => date('Y-m-d H:i:s'),
        'later' => $postData['send_datetime'],
        'recurring' => calculateNextSendTime($postData['recurring_days'], $postData['recurring_time']),
        default => date('Y-m-d H:i:s')
    };

    $scheduleId = createSchedule([
        'message_id' => $messageId,
        'recipient_id' => $postData['recipient_id'],
        'send_time' => $sendTime,
        'status' => $postData['send_type'] === 'now' ? 'pending' : 'pending',
        'is_recurring' => $postData['send_type'] === 'recurring',
        'recurring_days' => $postData['recurring_days'] ?? null,
        'recurring_time' => $postData['recurring_time'] ?? null
    ]);

    logActivity($userId, 'create_message', "Mensaje creado ID: {$messageId}, Programación ID: {$scheduleId}");

    return [
        'success' => true,
        'message_id' => $messageId,
        'schedule_id' => $scheduleId
    ];
}

function updateMessage(int $messageId, string $content): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("UPDATE messages SET content = ? WHERE id = ?");
    return $stmt->execute([$content, $messageId]);
}

function updateSchedule(int $scheduleId, array $data): bool
{
    $pdo = getDbConnection();
    
    $fields = [];
    $values = [];
    
    foreach ($data as $key => $value) {
        $fields[] = "{$key} = ?";
        $values[] = $value;
    }
    
    $values[] = $scheduleId;
    
    $sql = "UPDATE schedules SET " . implode(', ', $fields) . " WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    
    return $stmt->execute($values);
}

function handleEditMessage(int $messageId, array $postData): array
{
    if (empty($postData['content']) || empty($postData['recipient_id'])) {
        return ['success' => false, 'error' => 'Faltan campos requeridos'];
    }

    $userId = $_SESSION['user_id'] ?? 0;
    
    updateMessage($messageId, $postData['content']);

    if (!empty($postData['schedule_id'])) {
        $sendTime = match ($postData['send_type']) {
            'now' => date('Y-m-d H:i:s'),
            'later' => $postData['send_datetime'],
            'recurring' => calculateNextSendTime($postData['recurring_days'] ?? '', $postData['recurring_time'] ?? ''),
            default => $postData['send_datetime']
        };

        updateSchedule((int) $postData['schedule_id'], [
            'recipient_id' => $postData['recipient_id'],
            'send_time' => $sendTime,
            'is_recurring' => $postData['send_type'] === 'recurring',
            'recurring_days' => $postData['recurring_days'] ?? null,
            'recurring_time' => $postData['recurring_time'] ?? null,
            'status' => 'pending'
        ]);
    }

    logActivity($userId, 'edit_message', "Mensaje actualizado ID: {$messageId}");

    return ['success' => true, 'message_id' => $messageId];
}

function deleteMessage(int $messageId): bool
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("DELETE FROM schedules WHERE message_id = ?");
    $stmt->execute([$messageId]);
    
    $stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
    $result = $stmt->execute([$messageId]);
    
    if ($result) {
        logActivity($_SESSION['user_id'] ?? 0, 'delete_message', "Mensaje eliminado ID: {$messageId}");
    }
    
    return $result;
}

function getMessageById(int $messageId): ?array
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM messages WHERE id = ?");
    $stmt->execute([$messageId]);
    
    return $stmt->fetch() ?: null;
}

function getScheduleById(int $scheduleId): ?array
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM schedules WHERE id = ?");
    $stmt->execute([$scheduleId]);
    
    return $stmt->fetch() ?: null;
}

function getScheduledMessages(?int $userId = null): array
{
    $pdo = getDbConnection();
    
    $sql = "
        SELECT s.*, m.content, r.name as recipient_name, r.platform, r.platform_id
        FROM schedules s
        JOIN messages m ON s.message_id = m.id
        JOIN recipients r ON s.recipient_id = r.id
    ";
    
    if ($userId) {
        $sql .= " WHERE m.user_id = ?";
        $sql .= " ORDER BY s.send_time ASC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$userId]);
    } else {
        $sql .= " ORDER BY s.send_time ASC";
        $stmt = $pdo->query($sql);
    }
    
    return $stmt->fetchAll();
}

function getSentMessages(?int $userId = null, ?int $limit = 50): array
{
    $pdo = getDbConnection();
    
    $sql = "
        SELECT sm.*, r.name as recipient_name, r.platform, r.platform_id
        FROM sent_messages sm
        JOIN recipients r ON sm.recipient_id = r.id
    ";
    
    if ($userId) {
        $sql .= " WHERE sm.user_id = ?";
        $sql .= " ORDER BY sm.sent_at DESC LIMIT ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$userId, $limit]);
    } else {
        $sql .= " ORDER BY sm.sent_at DESC LIMIT ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$limit]);
    }
    
    return $stmt->fetchAll();
}
