<?php
ob_start(); // Start output buffering
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/buffer_helper.php';

$database = new Database();
$db = $database->getConnection();
$auth = new Auth($database);

// Handle activity operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $stmt = $db->prepare("INSERT INTO activities (name, date, location, time, description) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([
                    $_POST['name'],
                    $_POST['date'],
                    $_POST['location'],
                    $_POST['time'],
                    $_POST['description']
                ]);
                break;

            case 'edit':
                $stmt = $db->prepare("UPDATE activities SET name = ?, date = ?, location = ?, time = ?, description = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['name'],
                    $_POST['date'],
                    $_POST['location'],
                    $_POST['time'],
                    $_POST['description'],
                    $_POST['activity_id']
                ]);
                break;

            case 'delete':
                $stmt = $db->prepare("DELETE FROM activities WHERE id = ?");
                $stmt->execute([$_POST['activity_id']]);
                break;
        }
        safe_redirect('index.php?page=activities');
        exit();
    }
}

// Get all activities
$stmt = $db->query("SELECT * FROM activities ORDER BY date DESC, time DESC");
$activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col">
            <h2>إدارة الأنشطة</h2>
        </div>
        <div class="col-auto">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addActivityModal">
                <i class="bi bi-plus-circle"></i> إضافة نشاط جديد
            </button>
            <a href="?page=print_activities" class="btn btn-success" target="_blank">
                <i class="bi bi-printer"></i> طباعة تقرير الأنشطة
            </a>
        </div>
    </div>

    <!-- Calendar View -->
    <div class="row mb-4">
        <div class="col">
            <div class="card">
                <div class="card-body">
                    <div id="calendar"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Activities Table -->
    <div class="table-container">
        <table class="table table-striped datatable">
            <thead>
                <tr>
                    <th>اسم النشاط</th>
                    <th>التاريخ</th>
                    <th>الوقت</th>
                    <th>المكان</th>
                    <th>الوصف</th>
                    <th>العمليات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($activities as $activity): ?>
                <tr>
                    <td><?php echo htmlspecialchars($activity['name']); ?></td>
                    <td><?php echo htmlspecialchars($activity['date']); ?></td>
                    <td><?php echo htmlspecialchars($activity['time']); ?></td>
                    <td><?php echo htmlspecialchars($activity['location']); ?></td>
                    <td><?php echo htmlspecialchars($activity['description']); ?></td>
                    <td>
                        <button class="btn btn-sm btn-primary edit-activity" 
                                data-activity='<?php echo json_encode($activity); ?>'
                                data-bs-toggle="modal" 
                                data-bs-target="#editActivityModal">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <?php if ($auth->hasPermission('president')): ?>
                        <button class="btn btn-sm btn-danger delete-item" 
                                data-id="<?php echo $activity['id']; ?>"
                                data-type="النشاط"
                                data-name="<?php echo htmlspecialchars($activity['name']); ?>"
                                data-action="delete"
                                data-form-id="deleteActivityForm"
                                data-id-field="activity_id">
                            <i class="bi bi-trash"></i>
                        </button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Activity Modal -->
<div class="modal fade" id="addActivityModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">إضافة نشاط جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">اسم النشاط</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">التاريخ</label>
                        <input type="date" class="form-control" name="date" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الوقت</label>
                        <input type="time" class="form-control" name="time" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">المكان</label>
                        <input type="text" class="form-control" name="location" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الوصف</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </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>

<!-- Edit Activity Modal -->
<div class="modal fade" id="editActivityModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">تعديل النشاط</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="activity_id" id="edit_activity_id">
                    <div class="mb-3">
                        <label class="form-label">اسم النشاط</label>
                        <input type="text" class="form-control" name="name" id="edit_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">التاريخ</label>
                        <input type="date" class="form-control" name="date" id="edit_date" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الوقت</label>
                        <input type="time" class="form-control" name="time" id="edit_time" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">المكان</label>
                        <input type="text" class="form-control" name="location" id="edit_location" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الوصف</label>
                        <textarea class="form-control" name="description" id="edit_description" rows="3"></textarea>
                    </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>

<!-- Delete Activity Form -->
<form id="deleteActivityForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="activity_id" id="delete_activity_id">
</form>

<script>
$(document).ready(function() {
    // Initialize edit activity modal
    $('.edit-activity').click(function() {
        const activity = $(this).data('activity');
        $('#edit_activity_id').val(activity.id);
        $('#edit_name').val(activity.name);
        $('#edit_date').val(activity.date);
        $('#edit_time').val(activity.time);
        $('#edit_location').val(activity.location);
        $('#edit_description').val(activity.description);
    });

    // Handle activity deletion
    $('.delete-item').click(function() {
        const id = $(this).data('id');
        const type = $(this).data('type');
        const name = $(this).data('name');
        if (confirm(`هل أنت متأكد من حذف ${type} "${name}"؟`)) {
            const formId = $(this).data('form-id');
            const idField = $(this).data('id-field');
            $(`#${formId} #${idField}`).val(id);
            $(`#${formId}`).submit();
        }
    });

    // Initialize calendar
    if (typeof FullCalendar !== 'undefined') {
        const calendar = new FullCalendar.Calendar(document.getElementById('calendar'), {
            initialView: 'dayGridMonth',
            locale: 'ar',
            direction: 'rtl',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            events: <?php echo json_encode(array_map(function($activity) {
                return [
                    'title' => $activity['name'],
                    'start' => $activity['date'] . 'T' . $activity['time'],
                    'description' => $activity['description'],
                    'location' => $activity['location']
                ];
            }, $activities)); ?>
        });
        calendar.render();
    }
});
</script>

<!-- Add FullCalendar CSS and JS -->
<link href="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/main.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/main.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/locales/ar.js"></script>
