<?php
// academic_plans_list.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

$committeeId = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

// Handle deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $planId = (int)$_GET['delete'];
    
    // Check if plan exists and belongs to committee's scope
    $checkStmt = $mysqli1->prepare("
        SELECT ap.id FROM academic_plans ap 
        WHERE ap.id = ? AND ap.deleted_at IS NULL
        " . (!$canAll && $scopeCollege !== null ? " AND ap.college_id = ?" : "")
    );
    
    if (!$canAll && $scopeCollege !== null) {
        $checkStmt->bind_param('ii', $planId, $scopeCollege);
    } else {
        $checkStmt->bind_param('i', $planId);
    }
    
    $checkStmt->execute();
    $planExists = $checkStmt->get_result()->fetch_assoc();
    
    if ($planExists) {
        // Soft delete
        $deleteStmt = $mysqli1->prepare("UPDATE academic_plans SET deleted_at = NOW() WHERE id = ?");
        $deleteStmt->bind_param('i', $planId);
        
        if ($deleteStmt->execute()) {
            $_SESSION['success_message'] = "تم حذف الخطة الدراسية بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء الحذف";
        }
    } else {
        $_SESSION['error_message'] = "الخطة الدراسية غير موجودة أو ليس لديك صلاحية لحذفها";
    }
    
    header("Location: academic_plans_list.php");
    exit;
}

// Handle status toggle
if (isset($_GET['toggle_status']) && is_numeric($_GET['toggle_status'])) {
    $planId = (int)$_GET['toggle_status'];
    
    $checkStmt = $mysqli1->prepare("
        SELECT ap.id, ap.is_active FROM academic_plans ap 
        WHERE ap.id = ? AND ap.deleted_at IS NULL
        " . (!$canAll && $scopeCollege !== null ? " AND ap.college_id = ?" : "")
    );
    
    if (!$canAll && $scopeCollege !== null) {
        $checkStmt->bind_param('ii', $planId, $scopeCollege);
    } else {
        $checkStmt->bind_param('i', $planId);
    }
    
    $checkStmt->execute();
    $plan = $checkStmt->get_result()->fetch_assoc();
    
    if ($plan) {
        $newStatus = $plan['is_active'] ? 0 : 1;
        $toggleStmt = $mysqli1->prepare("UPDATE academic_plans SET is_active = ? WHERE id = ?");
        $toggleStmt->bind_param('ii', $newStatus, $planId);
        
        if ($toggleStmt->execute()) {
            $_SESSION['success_message'] = $newStatus ? "تم تفعيل الخطة الدراسية" : "تم إيقاف الخطة الدراسية";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء تغيير الحالة";
        }
    }
    
    header("Location: academic_plans_list.php");
    exit;
}

// Build query with filters
$search = trim($_GET['search'] ?? '');
$program_id = isset($_GET['program_id']) && $_GET['program_id'] !== '' ? (int)$_GET['program_id'] : null;
$college_id = isset($_GET['college_id']) && $_GET['college_id'] !== '' ? (int)$_GET['college_id'] : null;
$section_id = isset($_GET['section_id']) && $_GET['section_id'] !== '' ? (int)$_GET['section_id'] : null;
$is_active = isset($_GET['is_active']) && $_GET['is_active'] !== '' ? (int)$_GET['is_active'] : null;

$where = "WHERE ap.deleted_at IS NULL";
$types = '';
$params = [];

// Apply committee scope
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND ap.college_id = ?";
    $types .= 'i';
    $params[] = $scopeCollege;
}

// Apply filters
if ($search) {
    $where .= " AND (ap.plan_name LIKE ? OR ap.plan_code LIKE ?)";
    $types .= 'ss';
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($program_id !== null) {
    $where .= " AND ap.program_id = ?";
    $types .= 'i';
    $params[] = $program_id;
}

if ($college_id !== null && ($canAll || $college_id == $scopeCollege)) {
    $where .= " AND ap.college_id = ?";
    $types .= 'i';
    $params[] = $college_id;
}

if ($section_id !== null) {
    $where .= " AND ap.section_id = ?";
    $types .= 'i';
    $params[] = $section_id;
}

if ($is_active !== null) {
    $where .= " AND ap.is_active = ?";
    $types .= 'i';
    $params[] = $is_active;
}

// Get total count
$countQuery = "SELECT COUNT(*) as total FROM academic_plans ap $where";
$countStmt = $mysqli1->prepare($countQuery);
if ($types) $countStmt->bind_param($types, ...$params);
$countStmt->execute();
$countResult = $countStmt->get_result()->fetch_assoc();
$totalCount = $countResult['total'] ?? 0;
$countStmt->close();

// Pagination
$perPage = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$totalPages = ceil($totalCount / $perPage);

// Get plans with joins
$query = "
    SELECT 
        ap.*,
        c.name as college_name,
        sec.name as section_name,
        p.name as program_name,
        (SELECT COUNT(*) FROM academic_plan_subjects WHERE plan_id = ap.id) as total_subjects,
        (SELECT COUNT(DISTINCT semester_id) FROM academic_plan_subjects WHERE plan_id = ap.id) as total_semesters_used
    FROM academic_plans ap
    LEFT JOIN colleges c ON c.id = ap.college_id
    LEFT JOIN sections sec ON sec.id = ap.section_id
    LEFT JOIN programs p ON p.id = ap.program_id
    $where
    ORDER BY ap.created_at DESC
    LIMIT ? OFFSET ?
";

$types .= 'ii';
$params[] = $perPage;
$params[] = $offset;

$stmt = $mysqli1->prepare($query);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$plans = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get filter data
$colleges = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$programs = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$sections = $mysqli1->query("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>الخطط الدراسية - لوحة اللجنة</title>
    <link rel="stylesheet" href="css/style4.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        .navbar {
            background-color: white !important;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .navbar-brand {
            color: #1F3A2E !important;
        }
        
        .nav-link {
            color: #333 !important;
        }
        
        .nav-link:hover, .nav-link.active {
            color: #1F3A2E !important;
            background-color: rgba(31, 58, 46, 0.1);
        }
        
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        .status-active {
            background-color: rgba(39, 174, 96, 0.1);
            color: #27ae60;
            border: 1px solid rgba(39, 174, 96, 0.3);
        }
        .status-inactive {
            background-color: rgba(108, 117, 125, 0.1);
            color: #6c757d;
            border: 1px solid rgba(108, 117, 125, 0.3);
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .action-buttons .btn {
            width: 32px;
            height: 32px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }
        
        .bg-light {
            background-color: #f8fafc !important;
        }
        
        .plan-card {
            background: white;
            border-radius: 16px;
            padding: 16px;
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
        }
        
        .plan-card:hover {
            box-shadow: 0 10px 24px rgba(0,0,0,.1);
        }
        
        .stats-badge {
            background-color: #f0f2f5;
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 0.8rem;
        }
        
        .pagination .page-link {
            color: #1F3A2E;
        }
        .pagination .page-item.active .page-link {
            background-color: #1F3A2E;
            border-color: #1F3A2E;
            color: white;
        }
    </style>
</head>
<body class="bg-light">
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex align-items-center justify-content-between mb-4">
            <div>
                <h3 class="fw-bold text-dark mb-1">
                    <i class="fas fa-layer-group me-2"></i>الخطط الدراسية
                </h3>
                <p class="text-muted mb-0">إدارة وعرض جميع الخطط الدراسية في النظام</p>
            </div>
            <div>
                <a href="academic_plan_add.php" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i>إضافة خطة جديدة
                </a>
                <a href="exams_results.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-right me-2"></i>العودة للرئيسية
                </a>
            </div>
        </div>

        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?= e($_SESSION['success_message']) ?>
                <button type="button" class="btn-close float-start" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?= e($_SESSION['error_message']) ?>
                <button type="button" class="btn-close float-start" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Filter Card -->
      
<div class="filter-card">
    <form method="get" class="row g-3">
        <div class="col-md-3">
            <label class="form-label fw-semibold">بحث</label>
            <input type="text" class="form-control" name="search" placeholder="اسم الخطة أو الرمز" 
                   value="<?= e($search) ?>">
        </div>
        
        <div class="col-md-2">
            <label class="form-label fw-semibold">الكلية</label>
            <select class="form-select" name="college_id" onchange="this.form.submit()">
                <option value="">جميع الكليات</option>
                <?php foreach ($colleges as $college): ?>
                    <?php if ($canAll || $college['id'] == $scopeCollege): ?>
                        <option value="<?= e($college['id']) ?>" 
                            <?= ($college_id == $college['id']) ? 'selected' : '' ?>>
                            <?= e($college['name']) ?>
                        </option>
                    <?php endif; ?>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="col-md-2">
            <label class="form-label fw-semibold">القسم</label>
            <select class="form-select" name="section_id" onchange="this.form.submit()">
                <option value="">جميع الأقسام</option>
                <?php
                // Check if sections have parent/college_id field
                $hasParentField = isset($sections[0]['parent']) || isset($sections[0]['college_id']);
                
                if ($hasParentField && $college_id) {
                    // Filter sections by college
                    $filteredSections = array_filter($sections, function($s) use ($college_id) {
                        $parentValue = $s['parent'] ?? $s['college_id'] ?? null;
                        return $parentValue == $college_id;
                    });
                    
                    foreach ($filteredSections as $section): ?>
                        <option value="<?= e($section['id']) ?>" 
                            <?= ($section_id == $section['id']) ? 'selected' : '' ?>>
                            <?= e($section['name']) ?>
                        </option>
                    <?php endforeach;
                } elseif (!$hasParentField) {
                    // If no parent field, show all sections
                    foreach ($sections as $section): ?>
                        <option value="<?= e($section['id']) ?>" 
                            <?= ($section_id == $section['id']) ? 'selected' : '' ?>>
                            <?= e($section['name']) ?>
                        </option>
                    <?php endforeach;
                } else {
                    // Has parent field but no college selected
                    echo '<option value="" disabled>اختر الكلية أولاً</option>';
                }
                ?>
            </select>
            <?php if (!$hasParentField): ?>
                <small class="text-muted">(جميع الأقسام - بدون تصفية)</small>
            <?php endif; ?>
        </div>
        
        <div class="col-md-2">
            <label class="form-label fw-semibold">البرنامج</label>
            <select class="form-select" name="program_id" onchange="this.form.submit()">
                <option value="">جميع البرامج</option>
                <?php foreach ($programs as $program): ?>
                    <option value="<?= e($program['id']) ?>" 
                        <?= ($program_id == $program['id']) ? 'selected' : '' ?>>
                        <?= e($program['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="col-md-2">
            <label class="form-label fw-semibold">الحالة</label>
            <select class="form-select" name="is_active" onchange="this.form.submit()">
                <option value="">جميع الحالات</option>
                <option value="1" <?= ($is_active === 1) ? 'selected' : '' ?>>نشط</option>
                <option value="0" <?= ($is_active === 0) ? 'selected' : '' ?>>غير نشط</option>
            </select>
        </div>
        
        <div class="col-md-1 d-flex align-items-end">
            <button type="submit" class="btn btn-primary w-100">
                <i class="fas fa-filter"></i>
            </button>
        </div>
        
        <?php if ($search || $program_id !== null || $college_id !== null || $section_id !== null || $is_active !== null): ?>
            <div class="col-12">
                <a href="academic_plans_list.php" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-sync-alt me-1"></i>إعادة تعيين
                </a>
            </div>
        <?php endif; ?>
    </form>
</div>

        <!-- Plans List -->
        <div class="row">
            <?php if (empty($plans)): ?>
                <div class="col-12">
                    <div class="text-center py-5 bg-white rounded-4">
                        <i class="fas fa-folder-open fa-4x text-muted mb-3"></i>
                        <h5 class="text-muted">لا توجد خطط دراسية</h5>
                        <p class="text-muted mb-3">لم يتم إضافة أي خطط دراسية بعد</p>
                        <a href="academic_plan_add.php" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>إضافة خطة جديدة
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($plans as $plan): ?>
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="plan-card">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <span class="badge bg-light text-dark px-3 py-2 rounded-pill">
                                        <i class="fas fa-hashtag me-1"></i><?= e($plan['plan_code']) ?>
                                    </span>
                                </div>
                                <div>
                                    <?php if ($plan['is_active']): ?>
                                        <span class="status-badge status-active">
                                            <i class="fas fa-check-circle me-1"></i>نشط
                                        </span>
                                    <?php else: ?>
                                        <span class="status-badge status-inactive">
                                            <i class="fas fa-pause-circle me-1"></i>غير نشط
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <h5 class="fw-bold mb-2"><?= e($plan['plan_name']) ?></h5>
                            
                            <div class="mb-3">
                                <div class="text-muted small mb-1">
                                    <i class="fas fa-university me-1"></i><?= e($plan['college_name'] ?? 'غير محدد') ?>
                                </div>
                                <div class="text-muted small mb-1">
                                    <i class="fas fa-layer-group me-1"></i><?= e($plan['section_name'] ?? 'غير محدد') ?>
                                </div>
                                <div class="text-muted small">
                                    <i class="fas fa-graduation-cap me-1"></i><?= e($plan['program_name'] ?? 'غير محدد') ?>
                                </div>
                            </div>
                            
                            <div class="d-flex gap-2 mb-3">
                                <span class="stats-badge">
                                    <i class="fas fa-book me-1"></i><?= $plan['total_subjects'] ?? 0 ?> مادة
                                </span>
                                <span class="stats-badge">
                                    <i class="fas fa-calendar-alt me-1"></i><?= $plan['total_semesters_used'] ?? 0 ?> فصل
                                </span>
                                <span class="stats-badge">
                                    <i class="fas fa-clock me-1"></i><?= e($plan['total_credit_hours'] ?? 0) ?> ساعة
                                </span>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">
                                    <i class="fas fa-calendar-plus me-1"></i>
                                    <?= date('Y-m-d', strtotime($plan['created_at'])) ?>
                                </small>
                                
                                <div class="action-buttons">
                                    <a href="academic_plan_view.php?id=<?= $plan['id'] ?>" 
                                       class="btn btn-sm btn-outline-info" 
                                       title="عرض التفاصيل">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="academic_plan_edit.php?id=<?= $plan['id'] ?>" 
                                       class="btn btn-sm btn-outline-primary" 
                                       title="تعديل">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="academic_plans_list.php?toggle_status=<?= $plan['id'] ?>" 
                                       class="btn btn-sm btn-outline-<?= $plan['is_active'] ? 'warning' : 'success' ?>" 
                                       title="<?= $plan['is_active'] ? 'إيقاف' : 'تفعيل' ?>"
                                       onclick="return confirm('هل أنت متأكد من <?= $plan['is_active'] ? 'إيقاف' : 'تفعيل' ?> الخطة؟')">
                                        <i class="fas fa-<?= $plan['is_active'] ? 'pause' : 'play' ?>"></i>
                                    </a>
                                    <a href="academic_plans_list.php?delete=<?= $plan['id'] ?>" 
                                       class="btn btn-sm btn-outline-danger" 
                                       title="حذف"
                                       onclick="return confirm('هل أنت متأكد من حذف هذه الخطة؟')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
                
                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                    <div class="col-12">
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                    <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>">
                                                <?= $i ?>
                                            </a>
                                        </li>
                                    <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Statistics -->
        <?php
        $statsQuery = "
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active,
                SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive,
                SUM(total_credit_hours) as total_hours
            FROM academic_plans 
            WHERE deleted_at IS NULL
            " . (!$canAll && $scopeCollege !== null ? " AND college_id = " . intval($scopeCollege) : "");
        
        $statsResult = $mysqli1->query($statsQuery);
        if ($statsResult) {
            $stats = $statsResult->fetch_assoc();
            $totalStats = (int)($stats['total'] ?? 0);
            $activeStats = (int)($stats['active'] ?? 0);
            $inactiveStats = (int)($stats['inactive'] ?? 0);
            $totalHours = (float)($stats['total_hours'] ?? 0);
        } else {
            $totalStats = $activeStats = $inactiveStats = $totalHours = 0;
        }
        ?>
        
        <div class="row mt-4">
            <div class="col-md-3">
                <div class="bg-white p-3 rounded-4 text-center">
                    <h5 class="fw-bold text-primary mb-2">إجمالي الخطط</h5>
                    <div class="fs-1 fw-bold"><?= number_format($totalStats) ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="bg-white p-3 rounded-4 text-center">
                    <h5 class="fw-bold text-success mb-2">الخطط النشطة</h5>
                    <div class="fs-1 fw-bold"><?= number_format($activeStats) ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="bg-white p-3 rounded-4 text-center">
                    <h5 class="fw-bold text-warning mb-2">الخطط غير النشطة</h5>
                    <div class="fs-1 fw-bold"><?= number_format($inactiveStats) ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="bg-white p-3 rounded-4 text-center">
                    <h5 class="fw-bold text-info mb-2">إجمالي الساعات</h5>
                    <div class="fs-1 fw-bold"><?= number_format($totalHours) ?></div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    $(document).ready(function() {
        setTimeout(function() {
            $('.alert').alert('close');
        }, 5000);
    });
    </script>
</body>
</html>