<?php
require_once '../config.php';

// التحقق من تسجيل الدخول
requireLogin();

// معالجة البحث والفلترة
$searchTerm = isset($_GET['search']) ? sanitizeInput($_GET['search']) : '';
$coachFilter = isset($_GET['coach_id']) ? (int)$_GET['coach_id'] : 0;
$categoryFilter = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;
$dayFilter = isset($_GET['day']) ? (int)$_GET['day'] : -1;

// استعلام قائمة حصص التدريب
$query = "SELECT ts.*, c.name as category_name, 
          co.first_name || ' ' || co.last_name as coach_name 
          FROM training_sessions ts 
          LEFT JOIN categories c ON ts.category_id = c.id 
          LEFT JOIN coaches co ON ts.coach_id = co.id 
          WHERE 1=1";
$params = [];

// إضافة شروط البحث
if (!empty($searchTerm)) {
    $query .= " AND (ts.title LIKE :search OR ts.location LIKE :search)";
    $params[':search'] = "%$searchTerm%";
}

if ($coachFilter > 0) {
    $query .= " AND ts.coach_id = :coach_id";
    $params[':coach_id'] = $coachFilter;
}

if ($categoryFilter > 0) {
    $query .= " AND ts.category_id = :category_id";
    $params[':category_id'] = $categoryFilter;
}

if ($dayFilter >= 0 && $dayFilter <= 6) {
    $query .= " AND ts.day_of_week = :day";
    $params[':day'] = $dayFilter;
}

// ترتيب النتائج
$query .= " ORDER BY ts.day_of_week, ts.start_time";

// تنفيذ الاستعلام
$sessions = fetchAll($query, $params);

// الحصول على قائمة المدربين للفلتر
$coaches = fetchAll("SELECT id, first_name, last_name FROM coaches WHERE status = 'active' ORDER BY first_name, last_name");

// الحصول على قائمة الفئات للفلتر
$categories = fetchAll("SELECT id, name FROM categories ORDER BY name");

// عنوان الصفحة
$pageTitle = 'إدارة حصص التدريب';

// تضمين ملف الهيدر
include '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0"><i class="fas fa-calendar-alt me-2"></i> إدارة حصص التدريب</h1>
    <a href="<?php echo SITE_URL; ?>/training/add.php" class="btn btn-primary">
        <i class="fas fa-plus-circle"></i> إضافة حصة تدريب جديدة
    </a>
</div>

<!-- فلاتر البحث -->
<div class="card mb-4">
    <div class="card-body">
        <form method="get" action="" class="row g-3">
            <div class="col-md-3">
                <label for="search" class="form-label">بحث</label>
                <input type="text" class="form-control" id="search" name="search" value="<?php echo $searchTerm; ?>" placeholder="عنوان الحصة أو المكان...">
            </div>
            <div class="col-md-3">
                <label for="coach_id" class="form-label">المدرب</label>
                <select class="form-select" id="coach_id" name="coach_id">
                    <option value="0">جميع المدربين</option>
                    <?php foreach ($coaches as $coach): ?>
                        <option value="<?php echo $coach['id']; ?>" <?php echo ($coachFilter == $coach['id']) ? 'selected' : ''; ?>>
                            <?php echo $coach['first_name'] . ' ' . $coach['last_name']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label for="category_id" class="form-label">الفئة</label>
                <select class="form-select" id="category_id" name="category_id">
                    <option value="0">جميع الفئات</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?php echo $category['id']; ?>" <?php echo ($categoryFilter == $category['id']) ? 'selected' : ''; ?>>
                            <?php echo $category['name']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label for="day" class="form-label">اليوم</label>
                <select class="form-select" id="day" name="day">
                    <option value="-1">جميع الأيام</option>
                    <option value="0" <?php echo ($dayFilter === 0) ? 'selected' : ''; ?>>الأحد</option>
                    <option value="1" <?php echo ($dayFilter === 1) ? 'selected' : ''; ?>>الاثنين</option>
                    <option value="2" <?php echo ($dayFilter === 2) ? 'selected' : ''; ?>>الثلاثاء</option>
                    <option value="3" <?php echo ($dayFilter === 3) ? 'selected' : ''; ?>>الأربعاء</option>
                    <option value="4" <?php echo ($dayFilter === 4) ? 'selected' : ''; ?>>الخميس</option>
                    <option value="5" <?php echo ($dayFilter === 5) ? 'selected' : ''; ?>>الجمعة</option>
                    <option value="6" <?php echo ($dayFilter === 6) ? 'selected' : ''; ?>>السبت</option>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search"></i> بحث
                </button>
            </div>
        </form>
    </div>
</div>

<!-- عرض الجدول الأسبوعي -->
<div class="card mb-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-calendar-week me-2"></i> الجدول الأسبوعي للحصص</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th width="12%">الوقت</th>
                        <th width="12%">الأحد</th>
                        <th width="12%">الاثنين</th>
                        <th width="12%">الثلاثاء</th>
                        <th width="12%">الأربعاء</th>
                        <th width="12%">الخميس</th>
                        <th width="12%">الجمعة</th>
                        <th width="12%">السبت</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // تنظيم الحصص حسب الوقت واليوم
                    $timeSlots = [];
                    $days = [0, 1, 2, 3, 4, 5, 6]; // الأحد إلى السبت
                    
                    foreach ($sessions as $session) {
                        $timeKey = $session['start_time'] . ' - ' . $session['end_time'];
                        if (!isset($timeSlots[$timeKey])) {
                            $timeSlots[$timeKey] = array_fill(0, 7, []);
                        }
                        $timeSlots[$timeKey][$session['day_of_week']][] = $session;
                    }
                    
                    // ترتيب الفترات الزمنية
                    ksort($timeSlots);
                    
                    foreach ($timeSlots as $timeSlot => $daysData):
                    ?>
                        <tr>
                            <td class="align-middle font-weight-bold"><?php echo formatTime(explode(' - ', $timeSlot)[0]) . ' - ' . formatTime(explode(' - ', $timeSlot)[1]); ?></td>
                            <?php foreach ($days as $day): ?>
                                <td class="align-middle">
                                    <?php if (!empty($daysData[$day])): ?>
                                        <?php foreach ($daysData[$day] as $session): ?>
                                            <div class="session-card mb-2 p-2 rounded 
                                                <?php 
                                                if ($session['category_id'] % 5 == 0) echo 'bg-primary';
                                                elseif ($session['category_id'] % 5 == 1) echo 'bg-success';
                                                elseif ($session['category_id'] % 5 == 2) echo 'bg-info';
                                                elseif ($session['category_id'] % 5 == 3) echo 'bg-warning';
                                                else echo 'bg-danger';
                                                ?> text-white">
                                                <div class="fw-bold"><?php echo $session['title']; ?></div>
                                                <div class="small"><?php echo $session['category_name']; ?></div>
                                                <div class="small"><?php echo $session['coach_name'] ?: 'لا يوجد مدرب'; ?></div>
                                                <div class="small"><?php echo $session['location']; ?></div>
                                                <div class="mt-1">
                                                    <a href="<?php echo SITE_URL; ?>/training/edit.php?id=<?php echo $session['id']; ?>" class="btn btn-sm btn-light" title="تعديل">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="<?php echo SITE_URL; ?>/training/attendance_record.php?session_id=<?php echo $session['id']; ?>" class="btn btn-sm btn-light" title="سجل الحضور">
                                                        <i class="fas fa-clipboard-list"></i>
                                                    </a>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                    
                    <?php if (empty($timeSlots)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4">
                                <div class="alert alert-info mb-0">
                                    <i class="fas fa-info-circle me-2"></i> لا توجد حصص تدريب مطابقة لمعايير البحث.
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- قائمة حصص التدريب -->
<div class="card">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-list me-2"></i> قائمة حصص التدريب</h5>
    </div>
    <div class="card-body">
        <?php if (count($sessions) > 0): ?>
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>عنوان الحصة</th>
                            <th>الفئة</th>
                            <th>المدرب</th>
                            <th>اليوم</th>
                            <th>الوقت</th>
                            <th>المكان</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $dayNames = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
                        foreach ($sessions as $index => $session): 
                        ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><?php echo $session['title']; ?></td>
                                <td><?php echo $session['category_name']; ?></td>
                                <td><?php echo $session['coach_name'] ?: 'لا يوجد مدرب'; ?></td>
                                <td><?php echo $dayNames[$session['day_of_week']]; ?></td>
                                <td><?php echo formatTime($session['start_time']) . ' - ' . formatTime($session['end_time']); ?></td>
                                <td><?php echo $session['location']; ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="<?php echo SITE_URL; ?>/training/edit.php?id=<?php echo $session['id']; ?>" class="btn btn-primary" title="تعديل">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="<?php echo SITE_URL; ?>/training/attendance_record.php?session_id=<?php echo $session['id']; ?>" class="btn btn-info" title="سجل الحضور">
                                            <i class="fas fa-clipboard-list"></i>
                                        </a>
                                        <a href="<?php echo SITE_URL; ?>/training/delete.php?id=<?php echo $session['id']; ?>" class="btn btn-danger btn-delete" title="حذف" onclick="return confirm('هل أنت متأكد من رغبتك في حذف هذه الحصة؟')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i> لا توجد حصص تدريب مطابقة لمعايير البحث.
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.session-card {
    transition: all 0.3s ease;
}
.session-card:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
</style>

<?php
// تضمين ملف الفوتر
include '../includes/footer.php';
?>
