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

$pageTitle = 'Editar Mensaje';

$messageId = $_GET['id'] ?? null;
$message = null;
$schedule = null;
$error = '';

if (!$messageId) {
    header('Location: scheduled_messages.php');
    exit;
}

try {
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM messages WHERE id = ?");
    $stmt->execute([$messageId]);
    $message = $stmt->fetch();
    
    if ($message) {
        $stmt = $pdo->prepare("SELECT * FROM schedules WHERE message_id = ? ORDER BY id DESC LIMIT 1");
        $stmt->execute([$messageId]);
        $schedule = $stmt->fetch();
        
        $stmt = $pdo->query("SELECT * FROM recipients ORDER BY platform, name");
        $recipients = $stmt->fetchAll();
        
        $stmt = $pdo->query("SELECT * FROM recurrent_messages ORDER BY name");
        $templates = $stmt->fetchAll();
    }
} catch (Exception $e) {
    $error = $e->getMessage();
}

if (!$message) {
    echo "Mensaje no encontrado";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = handleEditMessage($messageId, $_POST);
    
    if ($result['success']) {
        header('Location: scheduled_messages.php?updated=1');
        exit;
    } else {
        $error = $result['error'];
    }
}

$sendType = 'later';
if ($schedule) {
    if ($schedule['is_recurring']) {
        $sendType = 'recurring';
    } elseif (strtotime($schedule['send_time']) <= time()) {
        $sendType = 'now';
    }
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-pencil"></i> Editar Mensaje</h2>
</div>

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

<form method="POST" id="messageForm">
    <input type="hidden" name="action" value="update">
    <input type="hidden" name="schedule_id" value="<?= $schedule['id'] ?? '' ?>">
    
    <div class="row">
        <div class="col-md-8">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0">
                    <h5 class="mb-0">Contenido del Mensaje</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Plantilla (opcional)</label>
                        <select class="form-select" id="templateSelect">
                            <option value="">-- Seleccionar plantilla --</option>
                            <?php foreach ($templates as $template): ?>
                                <option value="<?= htmlspecialchars($template['message_content']) ?>">
                                    <?= htmlspecialchars($template['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Mensaje</label>
                        <textarea name="content" id="messageContent" class="form-control" rows="10" required><?= htmlspecialchars($message['content'] ?? '') ?></textarea>
                        <small class="text-muted">Usa HTML básico: &lt;b&gt;, &lt;i&gt;, &lt;u&gt;, &lt;a href&gt;, &lt;img&gt;</small>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0">
                    <h5 class="mb-0">Destinatario</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="">-- Seleccionar --</option>
                            <option value="discord">Discord</option>
                            <option value="telegram">Telegram</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Destinatario</label>
                        <select name="recipient_id" id="recipientSelect" class="form-select" required>
                            <option value="">Selecciona una plataforma primero</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0">
                    <h5 class="mb-0">Programación</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Tipo de envío</label>
                        <select name="send_type" id="sendType" class="form-select" required>
                            <option value="now" <?= $sendType === 'now' ? 'selected' : '' ?>>Enviar ahora</option>
                            <option value="later" <?= $sendType === 'later' ? 'selected' : '' ?>>Programar para después</option>
                            <option value="recurring" <?= $sendType === 'recurring' ? 'selected' : '' ?>>Recurrente</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="datetimeField" style="display: <?= $sendType === 'later' ? 'block' : 'none' ?>;">
                        <label class="form-label">Fecha y hora</label>
                        <input type="datetime-local" name="send_datetime" class="form-control" value="<?= $schedule ? date('Y-m-d\TH:i', strtotime($schedule['send_time'])) : '' ?>">
                    </div>
                    
                    <div id="recurringFields" style="display: <?= $sendType === 'recurring' ? 'block' : 'none' ?>;">
                        <div class="mb-3">
                            <label class="form-label">Días</label>
                            <select name="recurring_days" class="form-select">
                                <option value="monday" <?= ($schedule['recurring_days'] ?? '') === 'monday' ? 'selected' : '' ?>>Lunes</option>
                                <option value="tuesday" <?= ($schedule['recurring_days'] ?? '') === 'tuesday' ? 'selected' : '' ?>>Martes</option>
                                <option value="wednesday" <?= ($schedule['recurring_days'] ?? '') === 'wednesday' ? 'selected' : '' ?>>Miércoles</option>
                                <option value="thursday" <?= ($schedule['recurring_days'] ?? '') === 'thursday' ? 'selected' : '' ?>>Jueves</option>
                                <option value="friday" <?= ($schedule['recurring_days'] ?? '') === 'friday' ? 'selected' : '' ?>>Viernes</option>
                                <option value="saturday" <?= ($schedule['recurring_days'] ?? '') === 'saturday' ? 'selected' : '' ?>>Sábado</option>
                                <option value="sunday" <?= ($schedule['recurring_days'] ?? '') === 'sunday' ? 'selected' : '' ?>>Domingo</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Hora</label>
                            <input type="time" name="recurring_time" class="form-control" value="<?= $schedule['recurring_time'] ?? '09:00' ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="d-grid gap-2">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="bi bi-save"></i> Guardar Cambios
                </button>
                <a href="scheduled_messages.php" class="btn btn-outline-secondary">Cancelar</a>
            </div>
        </div>
    </div>
</form>

<script>
const recipients = <?= json_encode($recipients) ?>;
const currentRecipientId = <?= $schedule['recipient_id'] ?? 'null' ?>;
const currentPlatform = '<?= $recipients ? array_search($currentRecipientId, array_column($recipients, 'id')) !== false ? $recipients[array_search($currentRecipientId, array_column($recipients, 'id'))]['platform'] : '' : '' ?>';

document.getElementById('templateSelect').addEventListener('change', function() {
    if (this.value) {
        document.getElementById('messageContent').value = this.value;
    }
});

document.getElementById('platformSelect').addEventListener('change', function() {
    const platform = this.value;
    const recipientSelect = document.getElementById('recipientSelect');
    
    recipientSelect.innerHTML = '<option value="">-- Seleccionar --</option>';
    
    if (platform) {
        const filtered = recipients.filter(r => r.platform === platform);
        filtered.forEach(r => {
            const option = document.createElement('option');
            option.value = r.id;
            option.textContent = r.name + ' (' + r.type + ')';
            if (r.id === currentRecipientId) option.selected = true;
            recipientSelect.appendChild(option);
        });
    }
});

document.getElementById('sendType').addEventListener('change', function() {
    const datetimeField = document.getElementById('datetimeField');
    const recurringFields = document.getElementById('recurringFields');
    
    datetimeField.style.display = this.value === 'later' ? 'block' : 'none';
    recurringFields.style.display = this.value === 'recurring' ? 'block' : 'none';
});

if (currentPlatform) {
    document.getElementById('platformSelect').value = currentPlatform;
    document.getElementById('platformSelect').dispatchEvent(new Event('change'));
}
</script>

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