<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';

if (!isLoggedIn() || !isAdmin()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'اعلانات و پیام به نمایندگان';

$has_table = false;
try {
    $has_table = $pdo->query("SHOW TABLES LIKE 'announcements'")->rowCount() > 0;
} catch (Exception $e) {}

// Handle POST requests for add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $has_table) {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $type = in_array($_POST['type'] ?? '', ['message', 'ad', 'contest']) ? $_POST['type'] : 'message';
    $active = isset($_POST['active']) ? 1 : 0;
    $expires = !empty($_POST['expires_at']) ? date('Y-m-d H:i:s', strtotime($_POST['expires_at'])) : null;

    try {
        if ($_POST['action'] === 'add' && $title !== '') {
            $stmt = $pdo->prepare("INSERT INTO announcements (title, content, type, active, expires_at) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$title, $content, $type, $active, $expires]);
            setMessage('اعلان با موفقیت اضافه شد.');
        } elseif ($_POST['action'] === 'edit') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id > 0 && $title !== '') {
                $stmt = $pdo->prepare("UPDATE announcements SET title=?, content=?, type=?, active=?, expires_at=? WHERE id=?");
                $stmt->execute([$title, $content, $type, $active, $expires, $id]);
                setMessage('اعلان با موفقیت به‌روزرسانی شد.');
            }
        }
        redirect('announcements.php');
    } catch (Exception $e) {
        setMessage('خطایی رخ داد: ' . $e->getMessage(), 'error');
    }
}

// Handle delete request
if (isset($_GET['delete']) && $has_table) {
    $id = (int)$_GET['delete'];
    try {
        $pdo->prepare("DELETE FROM announcements WHERE id = ?")->execute([$id]);
        setMessage('اعلان حذف شد.');
        redirect('announcements.php');
    } catch (Exception $e) {
        setMessage('خطا در حذف: ' . $e->getMessage(), 'error');
    }
}

$list = $has_table ? $pdo->query("SELECT * FROM announcements ORDER BY created_at DESC")->fetchAll() : [];
$type_labels = ['message' => 'پیام', 'ad' => 'تبلیغ', 'contest' => 'جشنواره'];

require_once '../includes/header.php';
?>

<div class="card admin-main-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><i class="bi bi-megaphone me-2"></i><?= htmlspecialchars($page_title) ?></h3>
        <?php if ($has_table): ?>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEditModal" data-action="add">افزودن اعلان</button>
        <?php endif; ?>
    </div>
    <div class="card-body">
        <?php if (!$has_table): ?>
            <div class="alert alert-warning">جدول `announcements` یافت نشد. لطفاً برای ایجاد آن، اسکریپت <a href="../fix_database.php">fix_database.php</a> را اجرا کنید.</div>
        <?php elseif (empty($list)): ?>
            <div class="text-center text-muted py-4">در حال حاضر هیچ اعلانی ثبت نشده است.</div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>عنوان</th>
                            <th>نوع</th>
                            <th>وضعیت</th>
                            <th>تاریخ انقضا</th>
                            <th>تاریخ ثبت</th>
                            <th class="text-end">عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($list as $a): ?>
                            <tr>
                                <td><?= htmlspecialchars($a['title']) ?></td>
                                <td><span class="badge bg-soft-secondary"><?= $type_labels[$a['type']] ?? htmlspecialchars($a['type']) ?></span></td>
                                <td>
                                    <span class="badge <?= $a['active'] ? 'bg-success' : 'bg-danger' ?>">
                                        <?= $a['active'] ? 'فعال' : 'غیرفعال' ?>
                                    </span>
                                </td>
                                <td><?= $a['expires_at'] ? date('Y/m/d', strtotime($a['expires_at'])) : '-' ?></td>
                                <td><?= date('Y/m/d H:i', strtotime($a['created_at'])) ?></td>
                                <td class="text-end">
                                    <button type="button" class="btn btn-sm btn-primary" onclick='openEditModal(<?= json_encode($a, JSON_UNESCAPED_UNICODE) ?>)'>ویرایش</button>
                                    <a href="?delete=<?= $a['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('آیا از حذف این اعلان اطمینان دارید؟')">حذف</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add/Edit Modal -->
<?php if ($has_table): ?>
<div class="modal fade" id="addEditModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">افزودن اعلان</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" id="form_action" value="add">
                <input type="hidden" name="id" id="form_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="form_title" class="form-label">عنوان</label>
                        <input type="text" name="title" id="form_title" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="form_type" class="form-label">نوع</label>
                        <select name="type" id="form_type" class="form-select">
                            <option value="message">پیام</option>
                            <option value="ad">تبلیغ</option>
                            <option value="contest">جشنواره</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="form_content" class="form-label">متن (پشتیبانی از HTML)</label>
                        <textarea name="content" id="form_content" class="form-control" rows="5"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="form_expires_at" class="form-label">تاریخ انقضا (اختیاری)</label>
                            <input type="datetime-local" name="expires_at" id="form_expires_at" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3 d-flex align-items-end">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="active" id="form_active" value="1" checked>
                                <label class="form-check-label" for="form_active">فعال (نمایش به نمایندگان)</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-primary">ذخیره تغییرات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const addEditModal = document.getElementById('addEditModal');
    const modalTitle = document.getElementById('modalTitle');
    const formAction = document.getElementById('form_action');
    const formId = document.getElementById('form_id');
    const formTitle = document.getElementById('form_title');
    const formContent = document.getElementById('form_content');
    const formType = document.getElementById('form_type');
    const formActive = document.getElementById('form_active');
    const formExpiresAt = document.getElementById('form_expires_at');

    // Handle modal for adding
    const addButton = document.querySelector('button[data-action="add"]');
    if (addButton) {
        addButton.addEventListener('click', () => {
            modalTitle.textContent = 'افزودن اعلان';
            formAction.value = 'add';
            formId.value = '';
            addEditModal.querySelector('form').reset();
            formActive.checked = true;
        });
    }
});

function openEditModal(data) {
    const addEditModal = new bootstrap.Modal(document.getElementById('addEditModal'));
    document.getElementById('modalTitle').textContent = 'ویرایش اعلان';
    document.getElementById('form_action').value = 'edit';
    document.getElementById('form_id').value = data.id;
    document.getElementById('form_title').value = data.title || '';
    document.getElementById('form_content').value = data.content || '';
    document.getElementById('form_type').value = data.type || 'message';
    document.getElementById('form_active').checked = data.active == 1;
    
    if (data.expires_at) {
        // Convert Y-m-d H:i:s to a format suitable for datetime-local input
        const date = new Date(data.expires_at.replace(' ', 'T'));
        document.getElementById('form_expires_at').value = date.toISOString().slice(0, 16);
    } else {
        document.getElementById('form_expires_at').value = '';
    }
    
    addEditModal.show();
}
</script>
<?php endif; ?>

<?php require_once '../includes/footer.php'; ?>

