<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/settings.php';
require_once __DIR__ . '/includes/permissions.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

if (!canView('events')) {
    die("ليس لديك صلاحية لعرض هذه الصفحة");
}

try {
    $db = db();
    $stmt = $db->query("SELECT * FROM events ORDER BY event_date ASC, start_time ASC");
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("خطأ في قاعدة البيانات");
}

$settings = get_settings();
$logo_path = $settings['site_logo'] ?? '';

if (empty($logo_path) || !file_exists($logo_path)) {
    if (!empty($logo_path) && file_exists('uploads/charity/' . $logo_path)) {
        $logo_path = 'uploads/charity/' . $logo_path;
    } else {
        $possible_logos = glob('uploads/charity/*logo*.*');
        if (!empty($possible_logos)) {
            $logo_path = $possible_logos[0];
        } else {
            $logo_path = '';
        }
    }
}

$logo_html = '';
if ($logo_path) {
    $logo_html = '<img src="' . $logo_path . '" alt="Logo" style="max-height: 80px;">';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>طباعة الأحداث والتقويم</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @page {
            size: A4;
            margin: 1.5cm;
        }
        body {
            font-family: 'Cairo', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #fff;
            color: #333;
            margin: 0;
            padding: 20px;
            direction: rtl;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            border-bottom: 2px solid #00827F;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .header h1 {
            margin: 10px 0 5px;
            font-size: 24px;
            color: #00827F;
        }
        .header h2 {
            margin: 5px 0;
            font-size: 16px;
            color: #555;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 12px 8px;
            text-align: right;
        }
        th {
            background-color: #f4f7f6;
            color: #00827F;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #fafafa;
        }
        .no-print {
            position: fixed;
            top: 20px;
            left: 20px;
            background: #00827F;
            color: #fff;
            padding: 10px 25px;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            z-index: 1000;
            font-family: 'Cairo', sans-serif;
            font-weight: bold;
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            text-decoration: none;
            display: inline-block;
        }
        .date-badge {
            display: inline-block;
            background: #e9ecef;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
        }
        @media print {
            body { padding: 0; }
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <button class="no-print" onclick="window.print()">
        <i class="fas fa-print"></i> طباعة
    </button>

    <div class="container">
        <div class="header">
            <?php if ($logo_html): ?>
                <div style="margin-bottom: 10px;"><?= $logo_html ?></div>
            <?php endif; ?>
            <h1><?= htmlspecialchars($settings['site_name'] ?? 'النظام') ?></h1>
            <?php if (!empty($settings['site_slogan'])): ?>
                <h2><?= htmlspecialchars($settings['site_slogan']) ?></h2>
            <?php endif; ?>
            <div style="margin-top: 20px; font-size: 20px; font-weight: bold;">قائمة الأحداث والفعاليات</div>
        </div>

        <?php if (empty($events)): ?>
            <div style="text-align: center; padding: 50px; color: #777;">
                لا توجد أحداث مسجلة حالياً
            </div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="25%">عنوان الحدث</th>
                        <th width="15%">التاريخ</th>
                        <th width="15%">الوقت</th>
                        <th width="15%">المكان</th>
                        <th width="25%">التفاصيل</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $count = 1;
                    foreach ($events as $e): 
                        // Format date and time safely
                        $date_obj = date_create($e['event_date']);
                        $formatted_date = $date_obj ? date_format($date_obj, 'Y-m-d') : $e['event_date'];
                        
                        $time_str = '';
                        if (!empty($e['start_time'])) {
                            $time_str = date('H:i', strtotime($e['start_time']));
                            if (!empty($e['end_time'])) {
                                $time_str .= ' - ' . date('H:i', strtotime($e['end_time']));
                            }
                        }
                    ?>
                    <tr>
                        <td><?= $count++ ?></td>
                        <td><strong><?= htmlspecialchars($e['title'] ?? '') ?></strong></td>
                        <td><span class="date-badge"><?= $formatted_date ?></span></td>
                        <td><span dir="ltr"><?= htmlspecialchars($time_str) ?></span></td>
                        <td><?= htmlspecialchars($e['location'] ?? 'غير محدد') ?></td>
                        <td><?= nl2br(htmlspecialchars($e['description'] ?? '')) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <div style="margin-top: 30px; text-align: center; font-size: 12px; color: #999;">
            تم استخراج هذا المستند إلكترونياً من النظام بتاريخ <?= date('Y-m-d H:i') ?>
        </div>
    </div>
</body>
</html>