<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Get existing exam routines
$stmt = $pdo->query("
    SELECT DISTINCT e.*, c.name as class_name, c.section,
           COUNT(es.id) as subject_count
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    LEFT JOIN exam_subjects es ON e.id = es.exam_id
    GROUP BY e.id, c.name, c.section
    ORDER BY e.exam_date DESC, e.created_at DESC
");
$routines = $stmt->fetchAll();

// Handle form submission for updating exam subjects
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_subjects'])) {
    $exam_id = $_POST['exam_id'];
    $subjects_data = $_POST['subjects'] ?? [];
    $new_subjects = $_POST['new_subjects'] ?? [];
    $delete_subjects = $_POST['delete_subjects'] ?? [];
    
    try {
        $pdo->beginTransaction();
        
        // Update existing subjects
        foreach ($subjects_data as $subject_id => $subject_data) {
            if (!empty($subject_data['exam_date'])) {
                $stmt = $pdo->prepare("
                    UPDATE exam_subjects 
                    SET exam_date = ?, start_time = ?, end_time = ?
                    WHERE id = ? AND exam_id = ?
                ");
                $stmt->execute([
                    $subject_data['exam_date'],
                    $subject_data['start_time'] ?? '10:00:00',
                    $subject_data['end_time'] ?? '13:00:00',
                    $subject_id,
                    $exam_id
                ]);
            }
        }
        
        // Track duplicate subjects to show warning
        $duplicate_subjects = [];
        
        // Add new subjects
        foreach ($new_subjects as $new_subject) {
            if (!empty($new_subject['subject_id']) && !empty($new_subject['exam_date'])) {
                // Check if subject already exists for this exam
                $checkStmt = $pdo->prepare("SELECT id FROM exam_subjects WHERE exam_id = ? AND subject_id = ?");
                $checkStmt->execute([$exam_id, $new_subject['subject_id']]);
                
                if ($checkStmt->fetch()) {
                    // Subject already exists, add to duplicates list
                    $duplicate_subjects[] = $new_subject['subject_id'];
                    continue;
                }
                
                $stmt = $pdo->prepare("
                    INSERT INTO exam_subjects (exam_id, subject_id, max_marks, pass_marks, exam_date, start_time, end_time, marks) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $exam_id,
                    $new_subject['subject_id'],
                    $new_subject['max_marks'] ?? 100,
                    $new_subject['pass_marks'] ?? 40,
                    $new_subject['exam_date'],
                    $new_subject['start_time'] ?? '10:00:00',
                    $new_subject['end_time'] ?? '13:00:00',
                    $new_subject['marks'] ?? ''
                ]);
            }
        }
        
        // Add warning message for duplicate subjects
        if (!empty($duplicate_subjects)) {
            // Get subject names for the duplicates
            $subject_names = [];
            foreach ($duplicate_subjects as $subject_id) {
                foreach ($all_subjects as $subject) {
                    if ($subject['id'] == $subject_id) {
                        $subject_names[] = $subject['name'];
                        break;
                    }
                }
            }
            if (!empty($subject_names)) {
                $error_message .= " নিম্নলিখিত বিষয়গুলি ইতিমধ্যে এই পরীক্ষার জন্য যুক্ত করা হয়েছে: " . implode(', ', $subject_names) . ".";
            }
        }
        
        // Delete subjects
        foreach ($delete_subjects as $delete_subject_id) {
            $stmt = $pdo->prepare("DELETE FROM exam_subjects WHERE id = ? AND exam_id = ?");
            $stmt->execute([$delete_subject_id, $exam_id]);
        }
        
        $pdo->commit();
        $success_message = "পরীক্ষার বিষয়সমূহ সফলভাবে আপডেট করা হয়েছে!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = "ত্রুটি: " . $e->getMessage();
    }
}

// Get selected exam details and subjects
$selected_exam_id = $_GET['exam_id'] ?? $_POST['exam_id'] ?? '';
$exam_details = null;
$exam_subjects = [];

if ($selected_exam_id) {
    // Get exam details
    $stmt = $pdo->prepare("
        SELECT e.*, c.name as class_name, c.section
        FROM exams e
        JOIN classes c ON e.class_id = c.id
        WHERE e.id = ?
    ");
    $stmt->execute([$selected_exam_id]);
    $exam_details = $stmt->fetch();
    
    if ($exam_details) {
        // Get exam subjects
        $stmt = $pdo->prepare("
            SELECT es.*, s.name as subject_name, s.code as subject_code
            FROM exam_subjects es
            JOIN subjects s ON es.subject_id = s.id
            WHERE es.exam_id = ?
            ORDER BY es.exam_date, es.start_time
        ");
        $stmt->execute([$selected_exam_id]);
        $exam_subjects = $stmt->fetchAll();
    }
}

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$site_address = $settings['site_address'] ?? 'ঠিকানা, ফোন: ০১৭xxxxxxxx';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Get all subjects for adding new ones
$all_subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পরীক্ষার রুটিন বিষয় আপডেট - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            body { font-size: 12px; }
            .card { border: none; box-shadow: none; }
            .table { font-size: 11px; }
        }
        .print-only { display: none; }
        .routine-table th, .routine-table td {
            border: 1px solid #000 !important;
            padding: 8px !important;
            text-align: center;
        }
        .header-section {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #000;
            padding-bottom: 20px;
        }
        .header-section img {
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
        .subject-row {
            transition: background-color 0.3s;
        }
        .subject-row:hover {
            background-color: #f8f9fa;
        }
        
        .new-subject-row {
            background-color: #e8f5e9;
            border: 1px dashed #4caf50;
            margin-bottom: 10px;
            padding: 15px;
            border-radius: 5px;
        }
        
        .remove-subject-btn {
            cursor: pointer;
        }
        
        .delete-column {
            width: 80px;
            text-align: center;
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="routine.php">
                    <i class="fas fa-calendar"></i> পরীক্ষার রুটিন
                </a>
                <a class="nav-link" href="index.php">
                    <i class="fas fa-clipboard-list"></i> পরীক্ষা ব্যবস্থাপনা
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <!-- Select Exam Form -->
            <div class="col-md-4 no-print">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-search"></i> পরীক্ষা নির্বাচন করুন</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <form method="GET" action="">
                            <div class="mb-3">
                                <label for="exam_id" class="form-label">পরীক্ষা নির্বাচন করুন <span class="text-danger">*</span></label>
                                <select class="form-select" id="exam_id" name="exam_id" required onchange="this.form.submit()">
                                    <option value="">পরীক্ষা নির্বাচন করুন</option>
                                    <?php foreach ($routines as $routine): ?>
                                        <option value="<?php echo $routine['id']; ?>" <?php echo ($selected_exam_id == $routine['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($routine['name']); ?> - 
                                            <?php echo htmlspecialchars($routine['class_name']); ?><?php echo $routine['section'] ? ' (' . $routine['section'] . ')' : ''; ?>
                                            (<?php echo date('d/m/Y', strtotime($routine['exam_date'])); ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($exam_details): ?>
                <div class="card mt-3">
                    <div class="card-header">
                        <h5><i class="fas fa-info-circle"></i> পরীক্ষার তথ্য</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>পরীক্ষার নাম:</strong> <?php echo htmlspecialchars($exam_details['name']); ?></p>
                        <p><strong>শ্রেণি:</strong> <?php echo htmlspecialchars($exam_details['class_name']); ?><?php echo $exam_details['section'] ? ' (' . $exam_details['section'] . ')' : ''; ?></p>
                        <p><strong>সেশন:</strong> <?php echo htmlspecialchars($exam_details['session']); ?></p>
                        <?php if ($exam_details['group_name']): ?>
                            <p><strong>গ্রুপ:</strong> <?php echo htmlspecialchars($exam_details['group_name']); ?></p>
                        <?php endif; ?>
                        <p><strong>তারিখ:</strong> <?php echo date('d/m/Y', strtotime($exam_details['exam_date'])); ?></p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Update Subjects Form -->
            <div class="col-md-8">
                <?php if ($exam_details && !empty($exam_subjects)): ?>
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-edit"></i> পরীক্ষার বিষয়সমূহ আপডেট করুন</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="update_subjects" value="1">
                            <input type="hidden" name="exam_id" value="<?php echo $selected_exam_id; ?>">
                            
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>বিষয়</th>
                                            <th>তারিখ</th>
                                            <th>শুরুর সময়</th>
                                            <th>শেষ সময়</th>
                                            <th class="delete-column">ডিলেট</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($exam_subjects as $subject): ?>
                                        <tr class="subject-row">
                                            <td>
                                                <strong><?php echo htmlspecialchars($subject['subject_name']); ?></strong>
                                                <br><small class="text-muted"><?php echo htmlspecialchars($subject['subject_code']); ?></small>
                                            </td>
                                            <td>
                                                <input type="date" class="form-control" name="subjects[<?php echo $subject['id']; ?>][exam_date]" 
                                                       value="<?php echo $subject['exam_date']; ?>" required>
                                            </td>
                                            <td>
                                                <input type="time" class="form-control" name="subjects[<?php echo $subject['id']; ?>][start_time]" 
                                                       value="<?php echo $subject['start_time']; ?>" required>
                                            </td>
                                            <td>
                                                <input type="time" class="form-control" name="subjects[<?php echo $subject['id']; ?>][end_time]" 
                                                       value="<?php echo $subject['end_time']; ?>" required>
                                            </td>
                                            <td class="text-center delete-column">
                                                <input type="checkbox" name="delete_subjects[]" value="<?php echo $subject['id']; ?>" 
                                                       id="delete_<?php echo $subject['id']; ?>" class="delete-checkbox">
                                                <label for="delete_<?php echo $subject['id']; ?>" class="text-danger ms-1">ডিলেট</label>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> আপডেট করুন
                                </button>
                                <a href="routine.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> রুটিন পৃষ্ঠায় ফিরে যান
                                </a>
                            </div>
                            
                            <!-- Add New Subject Section -->
                            <div class="mt-4">
                                <h5><i class="fas fa-plus-circle"></i> নতুন বিষয় যুক্ত করুন</h5>
                                <div id="new-subjects-container">
                                    <!-- New subject rows will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-outline-primary mt-2" id="add-new-subject-btn">
                                    <i class="fas fa-plus"></i> নতুন বিষয় যুক্ত করুন
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <?php elseif ($selected_exam_id && !$exam_details): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> নির্বাচিত পরীক্ষা খুঁজে পাওয়া যায়নি।
                </div>
                <?php elseif ($selected_exam_id && $exam_details): ?>
                <?php if (empty($exam_subjects)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> এই পরীক্ষার জন্য কোন বিষয় যুক্ত করা হয়নি। নিচে নতুন বিষয় যুক্ত করুন।
                </div>
                <?php endif; ?>
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-edit"></i> পরীক্ষার বিষয়সমূহ আপডেট করুন</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="update_subjects" value="1">
                            <input type="hidden" name="exam_id" value="<?php echo $selected_exam_id; ?>">
                            
                            <?php if (!empty($exam_subjects)): ?>
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>বিষয়</th>
                                            <th>তারিখ</th>
                                            <th>শুরুর সময়</th>
                                            <th>শেষ সময়</th>
                                            <th class="delete-column">ডিলেট</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($exam_subjects as $subject): ?>
                                        <tr class="subject-row">
                                            <td>
                                                <strong><?php echo htmlspecialchars($subject['subject_name']); ?></strong>
                                                <br><small class="text-muted"><?php echo htmlspecialchars($subject['subject_code']); ?></small>
                                            </td>
                                            <td>
                                                <input type="date" class="form-control" name="subjects[<?php echo $subject['id']; ?>][exam_date]" 
                                                       value="<?php echo $subject['exam_date']; ?>" required>
                                            </td>
                                            <td>
                                                <input type="time" class="form-control" name="subjects[<?php echo $subject['id']; ?>][start_time]" 
                                                       value="<?php echo $subject['start_time']; ?>" required>
                                            </td>
                                            <td>
                                                <input type="time" class="form-control" name="subjects[<?php echo $subject['id']; ?>][end_time]" 
                                               value="<?php echo $subject['end_time']; ?>" required>
                                            </td>
                                            <td class="text-center delete-column">
                                                <input type="checkbox" name="delete_subjects[]" value="<?php echo $subject['id']; ?>" 
                                                       id="delete_<?php echo $subject['id']; ?>" class="delete-checkbox">
                                                <label for="delete_<?php echo $subject['id']; ?>" class="text-danger ms-1">ডিলেট</label>
                                            </td>                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php endif; ?>
                            
                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> আপডেট করুন
                                </button>
                                <a href="routine.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> রুটিন পৃষ্ঠায় ফিরে যান
                                </a>
                            </div>
                            
                            <!-- Add New Subject Section -->
                            <div class="mt-4">
                                <h5><i class="fas fa-plus-circle"></i> নতুন বিষয় যুক্ত করুন</h5>
                                <div id="new-subjects-container">
                                    <!-- New subject rows will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-outline-primary mt-2" id="add-new-subject-btn">
                                    <i class="fas fa-plus"></i> নতুন বিষয় যুক্ত করুন
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> বিষয়সমূহ আপডেট করতে একটি পরীক্ষা নির্বাচন করুন।
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const addSubjectBtn = document.getElementById('add-new-subject-btn');
            const container = document.getElementById('new-subjects-container');
            let subjectCounter = 0;
            
            // Sample subjects data (in a real app, this would come from PHP)
            const subjects = [
                <?php foreach ($all_subjects as $subject): ?>
                { id: <?php echo $subject['id']; ?>, name: "<?php echo addslashes($subject['name']); ?>", code: "<?php echo addslashes($subject['code']); ?>" },
                <?php endforeach; ?>
            ];
            
            addSubjectBtn.addEventListener('click', function() {
                subjectCounter++;
                
                const rowDiv = document.createElement('div');
                rowDiv.className = 'new-subject-row';
                rowDiv.innerHTML = `
                    <div class="row">
                        <div class="col-md-4">
                            <label class="form-label">বিষয় <span class="text-danger">*</span></label>
                            <select class="form-select" name="new_subjects[${subjectCounter}][subject_id]" required>
                                <option value="">বিষয় নির্বাচন করুন</option>
                                ${subjects.map(subject => 
                                    `<option value="${subject.id}">${subject.name} (${subject.code})</option>`
                                ).join('')}
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">তারিখ <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="new_subjects[${subjectCounter}][exam_date]" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">শুরুর সময়</label>
                            <input type="time" class="form-control" name="new_subjects[${subjectCounter}][start_time]" value="10:00">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">শেষ সময়</label>
                            <input type="time" class="form-control" name="new_subjects[${subjectCounter}][end_time]" value="13:00">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">পূর্ণ নম্বর</label>
                            <input type="number" class="form-control" name="new_subjects[${subjectCounter}][max_marks]" value="100" min="1">
                        </div>
                        <div class="col-md-12 mt-2">
                            <button type="button" class="btn btn-danger btn-sm remove-subject-btn">
                                <i class="fas fa-times"></i> মুছে ফেলুন
                            </button>
                        </div>
                    </div>
                `;
                
                container.appendChild(rowDiv);
                
                // Add event listener to remove button
                rowDiv.querySelector('.remove-subject-btn').addEventListener('click', function() {
                    rowDiv.remove();
                });
                
                // Set today's date as default for the first new subject
                if (subjectCounter === 1) {
                    const today = new Date().toISOString().split('T')[0];
                    rowDiv.querySelector('input[type="date"]').value = today;
                }
            });
            
            // Add confirmation for delete checkboxes
            document.addEventListener('change', function(e) {
                if (e.target.name === 'delete_subjects[]' && e.target.checked) {
                    const subjectName = e.target.closest('tr').querySelector('strong').textContent;
                    if (!confirm(`আপনি কি "${subjectName}" বিষয়টি মুছে ফেলতে চান?`)) {
                        e.target.checked = false;
                    }
                }
            });
            
            // Add confirmation for form submission if any subjects are marked for deletion
            document.querySelector('form').addEventListener('submit', function(e) {
                const deleteCheckboxes = document.querySelectorAll('input[name="delete_subjects[]"]:checked');
                if (deleteCheckboxes.length > 0) {
                    const subjectNames = [];
                    deleteCheckboxes.forEach(cb => {
                        subjectNames.push(cb.closest('tr').querySelector('strong').textContent);
                    });
                    if (!confirm(`আপনি কি নিম্নলিখিত বিষয়গুলি মুছে ফেলতে চান?\n\n${subjectNames.join('\n')}`)) {
                        e.preventDefault();
                    }
                }
            });
        });
    </script>
</body>
</html>