<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/session_check.php';
checkSession();
require_once __DIR__ . '/includes/message_handler.php';

$pageTitle = 'Enviar Plantilla';

$templates = [];
$recipients = [];

try {
    $pdo = getDbConnection();
    $stmt = $pdo->query("SELECT * FROM recurrent_messages ORDER BY name");
    $templates = $stmt->fetchAll();
    
    $stmt = $pdo->query("SELECT * FROM recipients ORDER BY platform, name");
    $recipients = $stmt->fetchAll();
} catch (Exception $e) {
    $error = $e->getMessage();
}

$success = '';
$sendError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $templateId = $_POST['template_id'];
    $platform = $_POST['platform'];
    $recipientIds = $_POST['recipient_ids'] ?? [];
    $sendType = $_POST['send_type'] ?? 'now';
    
    $template = null;
    foreach ($templates as $t) {
        if ($t['id'] == $templateId) {
            $template = $t;
            break;
        }
    }
    
    if (!$template) {
        $sendError = 'Plantilla no encontrada';
    } elseif (empty($recipientIds)) {
        $sendError = 'Selecciona al menos un destinatario';
    } else {
        foreach ($recipientIds as $recipientId) {
            $recipient = null;
            foreach ($recipients as $r) {
                if ($r['id'] == $recipientId && $r['platform'] === $platform) {
                    $recipient = $r;
                    break;
                }
            }
            
            if ($recipient) {
                $sendTime = $sendType === 'now' ? date('Y-m-d H:i:s') : ($_POST['send_datetime'] ?? date('Y-m-d H:i:s'));
                
                $messageId = createMessage([
                    'user_id' => getCurrentUserId(),
                    'content' => $template['message_content']
                ]);
                
                $scheduleId = createSchedule([
                    'message_id' => $messageId,
                    'recipient_id' => $recipientId,
                    'send_time' => $sendTime,
                    'status' => 'pending'
                ]);
                
                $success .= "Enviado a {$recipient['name']}<br>";
            }
        }
        
        if ($sendType === 'now') {
            require_once __DIR__ . '/process_queue.php';
            processScheduledMessages();
        }
    }
}

require_once __DIR__ . '/templates/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-send"></i> Enviar Plantilla</h2>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?= $success ?></div>
<?php endif; ?>

<?php if (isset($sendError)): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($sendError) ?></div>
<?php endif; ?>

<form method="POST">
    <div class="row">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0">
                    <h5 class="mb-0">Seleccionar Plantilla</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($templates)): ?>
                        <p class="text-muted">No hay plantillas disponibles</p>
                    <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($templates as $template): ?>
                            <label class="list-group-item">
                                <input type="radio" name="template_id" value="<?= $template['id'] ?>" <?= $_POST['template_id'] == $template['id'] ? 'checked' : '' ?> required>
                                <strong><?= htmlspecialchars($template['name']) ?></strong>
                                <?php if ($template['telegram_command']): ?>
                                    <span class="badge bg-secondary">#<?= htmlspecialchars($template['telegram_command']) ?></span>
                                <?php endif; ?>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0">
                    <h5 class="mb-0">Destinatarios</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Plataforma</label>
                        <select name="platform" id="platformSelect" class="form-select" required>
                            <option value="discord">Discord</option>
                            <option value="telegram">Telegram</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Seleccionar destinatarios</label>
                        <div id="recipientsList" class="border rounded p-2" style="max-height: 200px; overflow-y: auto;">
                            <p class="text-muted small">Selecciona una plataforma primero</p>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Tipo de envío</label>
                        <select name="send_type" class="form-select">
                            <option value="now">Enviar ahora</option>
                            <option value="later">Programar</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="datetimeField" style="display: none;">
                        <label class="form-label">Fecha y hora</label>
                        <input type="datetime-local" name="send_datetime" class="form-control">
                    </div>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary btn-lg w-100">
                <i class="bi bi-send"></i> Enviar
            </button>
        </div>
    </div>
</form>

<script>
const recipients = <?= json_encode($recipients) ?>;

document.getElementById('platformSelect').addEventListener('change', function() {
    const platform = this.value;
    const list = document.getElementById('recipientsList');
    
    const filtered = recipients.filter(r => r.platform === platform);
    
    if (filtered.length === 0) {
        list.innerHTML = '<p class="text-muted small">No hay destinatarios para esta plataforma</p>';
    } else {
        list.innerHTML = filtered.map(r => `
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="recipient_ids[]" value="${r.id}" id="recipient_${r.id}">
                <label class="form-check-label" for="recipient_${r.id}">${r.name} (${r.type})</label>
            </div>
        `).join('');
    }
});

document.querySelector('select[name="send_type"]').addEventListener('change', function() {
    document.getElementById('datetimeField').style.display = this.value === 'later' ? 'block' : 'none';
});
</script>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
