<?php
$content = file_get_contents('events.php');

$search = <<<EOT
    if ($action === 'save' && ($can_add || $can_edit)) {
        $id = $_POST['id'] ?? 0;
        $title = $_POST['title'] ?? '';
        $date = $_POST['event_date'] ?? '';
        $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
        $end_time = !empty($_POST['end_time']) ? $_POST['end_time'] : null;
        $location = $_POST['location'] ?? '';
        $description = $_POST['description'] ?? '';

        if (!$title || !$date) {
            echo json_encode(['success' => false, 'error' => 'البيانات الأساسية مطلوبة']);
            exit;
        }

        if ($id && $can_edit) {
            $stmt = db()->prepare("UPDATE events SET title=?, description=?, event_date=?, start_time=?, end_time=?, location=? WHERE id=?");
            $stmt->execute([$title, $description, $date, $start_time, $end_time, $location, $id]);
        } elseif (!$id && $can_add) {
            $stmt = db()->prepare("INSERT INTO events (title, description, event_date, start_time, end_time, location, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$title, $description, $date, $start_time, $end_time, $location, $_SESSION['user_id']]);
        }
        
        echo json_encode(['success' => true]);
        exit;
    }
EOT;

$replace = <<<EOT
    if ($action === 'save') {
        $id = $_POST['id'] ?? 0;
        $title = $_POST['title'] ?? '';
        $date = $_POST['event_date'] ?? '';
        $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
        $end_time = !empty($_POST['end_time']) ? $_POST['end_time'] : null;
        $location = $_POST['location'] ?? '';
        $description = $_POST['description'] ?? '';

        if (!$title || !$date) {
            echo json_encode(['success' => false, 'error' => 'البيانات الأساسية مطلوبة']);
            exit;
        }

        try {
            if ($id && $can_edit) {
                $stmt = db()->prepare("UPDATE events SET title=?, description=?, event_date=?, start_time=?, end_time=?, location=? WHERE id=?");
                $stmt->execute([$title, $description, $date, $start_time, $end_time, $location, $id]);
            } elseif (!$id && $can_add) {
                $stmt = db()->prepare("INSERT INTO events (title, description, event_date, start_time, end_time, location, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$title, $description, $date, $start_time, $end_time, $location, $_SESSION['user_id']]);
            } else {
                echo json_encode(['success' => false, 'error' => 'ليس لديك صلاحية لإضافة أو تعديل الأحداث. يرجى تفعيل هذه الصلاحيات من "إدارة المستخدمين" أولاً.']);
                exit;
            }
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => 'خطأ قاعدة البيانات: ' . $e->getMessage()]);
        }
        exit;
    }
EOT;

$content = str_replace($search, $replace, $content);

$search2 = <<<EOT
    fetch('events.php?ajax=1', {
        method: 'POST',
        body: new FormData(form)
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            eventModal.hide();
            calendar.refetchEvents();
            Swal.fire({icon: 'success', title: 'تم الحفظ', showConfirmButton: false, timer: 1500});
        } else {
            Swal.fire({icon: 'error', title: 'خطأ', text: res.error || 'حدث خطأ أثناء الحفظ'});
        }
    });
EOT;

$replace2 = <<<EOT
    fetch('events.php?ajax=1', {
        method: 'POST',
        body: new FormData(form)
    })
    .then(r => {
        if (!r.ok) throw new Error("Network Error");
        return r.json();
    })
    .then(res => {
        if (res.success) {
            eventModal.hide();
            calendar.refetchEvents();
            Swal.fire({icon: 'success', title: 'تم الحفظ', showConfirmButton: false, timer: 1500});
        } else {
            Swal.fire({icon: 'error', title: 'خطأ', text: res.error || 'حدث خطأ أثناء الحفظ'});
        }
    })
    .catch(err => {
        console.error(err);
        Swal.fire({icon: 'error', title: 'حدث خطأ غير متوقع', text: 'ربما تكون جلسة تسجيل الدخول قد انتهت أو لا توجد صلاحيات كافية، يرجى تحديث الصفحة والمحاولة مجدداً.'});
    });
EOT;

$content = str_replace($search2, $replace2, $content);

file_put_contents('events.php', $content);
echo "Patched events.php successfully.\n";

