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

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

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

// Apply filters
if ($search) {
    $where .= " AND (s.subjectcode LIKE ? OR s.subjectnamea LIKE ? OR s.subjectnamee LIKE ?)";
    $types .= 'sss';
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

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

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

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

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

// Get total count
$countQuery = "SELECT COUNT(*) as total FROM subjects s $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 subjects with joins
$query = "
    SELECT 
        s.*,
        p.name as program_name,
        c.name as college_name,
        sec.name as section_name
    FROM subjects s
    LEFT JOIN programs p ON p.id = s.program_id
    LEFT JOIN colleges c ON c.id = s.college_id
    LEFT JOIN sections sec ON sec.id = s.section_id
    $where
    ORDER BY s.created_at DESC
    LIMIT ? OFFSET ?
";

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

$stmt = $mysqli1->prepare($query);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$subjects = $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>
        /* Override green navbar */
        .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);
        }
        
        .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: 28px;
            height: 28px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .pagination .page-link {
            color: #1F3A2E;
        }
        .pagination .page-item.active .page-link {
            background-color: #1F3A2E;
            border-color: #1F3A2E;
            color: white;
        }
        .dash-card {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            padding: 20px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .bg-light {
            background-color: #f8fafc !important;
        }
        
        /* Circle status indicator */
        .status-circle {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-left: 5px;
        }
        .status-circle-active {
            background-color: #27ae60;
            box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.2);
        }
        .status-circle-inactive {
            background-color: #e74c3c;
            box-shadow: 0 0 0 3px rgba(231, 76, 60, 0.2);
        }
        .status-text {
            font-size: 0.85rem;
            font-weight: 600;
        }
        
        /* Credit hours badge */
        .credit-hours-badge {
            background-color: rgba(13, 110, 253, 0.1);
            color: #0d6efd;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            border: 1px solid rgba(13, 110, 253, 0.2);
        }
    </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-book me-2"></i>إدارة المقررات الدراسية
                </h3>
                <p class="text-muted mb-0">إدارة وعرض جميع المقررات الدراسية في النظام</p>
            </div>
            <div>
                <a href="subjects_add.php" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i>إضافة مادة جديدة
                </a>
                <a href="committee_dashboard.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">
                        <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="program_id">
                        <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="section_id">
                        <option value="">جميع الأقسام</option>
                        <?php foreach ($sections as $section): ?>
                            <option value="<?= e($section['id']) ?>" 
                                <?= ($section_id == $section['id']) ? 'selected' : '' ?>>
                                <?= e($section['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">
                        <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="subjects_list.php" class="btn btn-outline-secondary btn-sm">
                            <i class="fas fa-sync-alt me-1"></i>إعادة تعيين
                        </a>
                        <span class="text-muted small ms-2">
                            <?= number_format($totalCount) ?> نتيجة
                        </span>
                    </div>
                <?php endif; ?>
            </form>
        </div>

        <!-- Subjects Table -->
        <div class="card card-arabic">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="80">رمز المادة</th>
                                <th>اسم المادة (عربي)</th>
                                <th>اسم المادة (إنجليزي)</th>
                                <th>الكلية</th>
                                <th>البرنامج</th>
                                <th>القسم</th>
                                <th width="100">ساعات معتمدة</th>
                                <th width="80">الحالة</th>
                                <th width="120">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($subjects)): ?>
                                <tr>
                                    <td colspan="9" class="text-center py-4 text-muted">
                                        <i class="fas fa-inbox fa-2x mb-3"></i>
                                        <div>لا توجد مواد دراسية لعرضها</div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($subjects as $subject): ?>
                                    <tr>
                                        <td>
                                            <code><?= e($subject['subjectcode']) ?></code>
                                        </td>
                                        <td>
                                            <strong><?= e($subject['subjectnamea']) ?></strong>
                                        </td>
                                        <td class="text-muted">
                                            <?= e($subject['subjectnamee']) ?>
                                        </td>
                                        <td>
                                            <?= e($subject['college_name'] ?? 'غير محدد') ?>
                                        </td>
                                        <td>
                                            <?= e($subject['program_name'] ?? 'غير محدد') ?>
                                        </td>
                                        <td>
                                            <?= e($subject['section_name'] ?? 'غير محدد') ?>
                                        </td>
                                        <td class="text-center">
                                            <span class="credit-hours-badge">
                                                <?= e($subject['credit_hours']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <span class="status-circle <?= $subject['is_active'] ? 'status-circle-active' : 'status-circle-inactive' ?>"></span>
                                                <span class="status-text ms-2">
                                                    <?= $subject['is_active'] ? 'نشط' : 'غير نشط' ?>
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <a href="subjects_edit.php?id=<?= $subject['id'] ?>" 
                                                   class="btn btn-sm btn-outline-primary" 
                                                   title="تعديل">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="subjects_list.php?toggle_status=<?= $subject['id'] ?>" 
                                                   class="btn btn-sm btn-outline-<?= $subject['is_active'] ? 'warning' : 'success' ?>" 
                                                   title="<?= $subject['is_active'] ? 'إيقاف' : 'تفعيل' ?>"
                                                   onclick="return confirm('هل أنت متأكد من <?= $subject['is_active'] ? 'إيقاف' : 'تفعيل' ?> المادة؟')">
                                                    <i class="fas fa-<?= $subject['is_active'] ? 'pause' : 'play' ?>"></i>
                                                </a>
                                                <a href="subjects_list.php?delete=<?= $subject['id'] ?>" 
                                                   class="btn btn-sm btn-outline-danger" 
                                                   title="حذف"
                                                   onclick="return confirm('هل أنت متأكد من حذف هذه المادة؟')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <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>
                <div class="text-center text-muted small mt-2">
                    الصفحة <?= $page ?> من <?= $totalPages ?> • إجمالي <?= number_format($totalCount) ?> مادة
                </div>
            </nav>
        <?php endif; ?>

        <!-- 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
            FROM subjects 
            WHERE deleted_at IS NULL
            " . (!$canAll && $scopeCollege !== null ? " AND college_id = " . intval($scopeCollege) : "");
        
        $statsResult = $mysqli1->query($statsQuery);
        if ($statsResult) {
            $stats = $statsResult->fetch_assoc();
            // Ensure values are not null
            $totalStats = (int)($stats['total'] ?? 0);
            $activeStats = (int)($stats['active'] ?? 0);
            $inactiveStats = (int)($stats['inactive'] ?? 0);
        } else {
            $totalStats = $activeStats = $inactiveStats = 0;
        }
        ?>
        
        <div class="row mt-4">
            <div class="col-md-4">
                <div class="dash-card text-center">
                    <h5 class="fw-bold text-primary mb-2">إجمالي المقررات</h5>
                    <div class="fs-1 fw-bold"><?= number_format($totalStats) ?></div>
                    <div class="text-muted small">مادة دراسية</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="dash-card text-center">
                    <h5 class="fw-bold text-success mb-2">المقررات النشطة</h5>
                    <div class="fs-1 fw-bold"><?= number_format($activeStats) ?></div>
                    <div class="text-muted small">مادة نشطة</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="dash-card text-center">
                    <h5 class="fw-bold text-warning mb-2">المقررات غير النشطة</h5>
                    <div class="fs-1 fw-bold"><?= number_format($inactiveStats) ?></div>
                    <div class="text-muted small">مادة غير نشطة</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>
    // Auto-hide alerts after 5 seconds
    $(document).ready(function() {
        setTimeout(function() {
            $('.alert').alert('close');
        }, 5000);
        
        // Confirmation for delete
        $('.btn-outline-danger').on('click', function(e) {
            if (!confirm('هل أنت متأكد من حذف هذه المادة؟')) {
                e.preventDefault();
            }
        });
        
        // Confirmation for status toggle
        $('.btn-outline-warning, .btn-outline-success').on('click', function(e) {
            var action = $(this).hasClass('btn-outline-warning') ? 'إيقاف' : 'تفعيل';
            if (!confirm('هل أنت متأكد من ' + action + ' المادة؟')) {
                e.preventDefault();
            }
        });
    });
    </script>
</body>
</html>