<?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();
}

$exam_id = $_GET['id'] ?? '';

if (!$exam_id) {
    header('Location: routine.php');
    exit();
}

// 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([$exam_id]);
$exam_details = $stmt->fetch();

if (!$exam_details) {
    header('Location: routine.php');
    exit();
}

// 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([$exam_id]);
$exam_subjects = $stmt->fetchAll();

// Get data for dropdowns
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();

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

// Handle form submission for updating exam routine
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_routine'])) {
    $exam_name = trim($_POST['exam_name']);
    $class_id = $_POST['class_id'];
    $session = $_POST['session'];
    $group_name = $_POST['group_name'] ?? '';
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    // Custom institution fields
    $custom_institution_name = trim($_POST['custom_institution_name'] ?? '');
    $custom_institution_address = trim($_POST['custom_institution_address'] ?? '');
    
    if (empty($exam_name)) {
        $error_message = 'পরীক্ষার নাম লিখুন';
    }
    
    if (empty($error_message)) {
        try {
            $pdo->beginTransaction();
            
            // Update main exam record
            $stmt = $pdo->prepare("UPDATE exams SET name = ?, class_id = ?, session = ?, group_name = ?, exam_date = ?, custom_institution_name = ?, custom_institution_address = ? WHERE id = ?");
            $stmt->execute([$exam_name, $class_id, $session, $group_name, $start_date, $custom_institution_name, $custom_institution_address, $exam_id]);
            
            $pdo->commit();
            $success_message = "পরীক্ষার রুটিন সফলভাবে আপডেট করা হয়েছে!";
            
            // Refresh exam details after update
            $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([$exam_id]);
            $exam_details = $stmt->fetch();
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}

// 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;
$logo_opacity = isset($settings['logo_opacity']) ? floatval($settings['logo_opacity']) : 0.9;
?>

<!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;
        }
    </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="attendance.php">
                    <i class="fas fa-clipboard-check"></i> হাজিরা পত্র
                </a>
                <a class="nav-link" href="seat_card.php">
                    <i class="fas fa-id-card"></i> সীট কার্ড
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <!-- Edit Routine Form -->
            <div class="col-md-12 no-print">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-edit"></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="POST" action="">
                            <input type="hidden" name="update_routine" value="1">
                            
                            <div class="mb-3">
                                <label for="exam_name" class="form-label">পরীক্ষার নাম <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="exam_name" name="exam_name" value="<?php echo htmlspecialchars($exam_details['name']); ?>" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="class_id" class="form-label">ক্লাস <span class="text-danger">*</span></label>
                                        <select class="form-select" id="class_id" name="class_id" required>
                                            <option value="">নির্বাচন করুন</option>
                                            <?php foreach ($classes as $class): ?>
                                                <option value="<?php echo $class['id']; ?>" <?php echo ($exam_details['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="session" class="form-label">সেশন <span class="text-danger">*</span></label>
                                        <select class="form-select" id="session" name="session" required>
                                            <option value="">নির্বাচন করুন</option>
                                            <?php foreach ($sessions as $session_row): ?>
                                                <option value="<?php echo htmlspecialchars($session_row['session_name']); ?>" <?php echo ($exam_details['session'] == $session_row['session_name']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($session_row['session_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="group_name" class="form-label">গ্রুপ</label>
                                        <select class="form-select" id="group_name" name="group_name">
                                            <option value="">General</option>
                                            <?php foreach ($groups as $group): ?>
                                                <option value="<?php echo htmlspecialchars($group['group_name']); ?>" <?php echo ($exam_details['group_name'] == $group['group_name']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($group['group_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="start_date" class="form-label">শুরুর তারিখ <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $exam_details['exam_date']; ?>" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="end_date" class="form-label">শেষের তারিখ <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $exam_details['exam_date']; ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Custom Institution Fields -->
                            <div class="mb-3">
                                <label for="custom_institution_name" class="form-label">প্রতিষ্ঠানের নাম (কাস্টম)</label>
                                <input type="text" class="form-control" id="custom_institution_name" name="custom_institution_name" placeholder="প্রতিষ্ঠানের নাম (যদি ডিফল্ট থেকে আলাদা হয়)" value="<?php echo htmlspecialchars($exam_details['custom_institution_name'] ?? ''); ?>">
                                <div class="form-text">সাইট সেটিং এ যে নাম ঠিকানা দেওয়া থাকবে তা অটো বসবে, প্রয়োজনে কাষ্টমাইজ করুন</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="custom_institution_address" class="form-label">প্রতিষ্ঠানের ঠিকানা (কাস্টম)</label>
                                <input type="text" class="form-control" id="custom_institution_address" name="custom_institution_address" placeholder="প্রতিষ্ঠানের ঠিকানা (যদি ডিফল্ট থেকে আলাদা হয়)" value="<?php echo htmlspecialchars($exam_details['custom_institution_address'] ?? ''); ?>">
                                <div class="form-text">সাইট সেটিং এ যে নাম ঠিকানা দেওয়া থাকবে তা অটো বসবে, প্রয়োজনে কাষ্টমাইজ করুন</div>
                            </div>
                            
                            <div class="d-grid gap-2 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>
                        </form>
                    </div>
                </div>
                
                <!-- Current Routine Preview -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h5><i class="fas fa-eye"></i> বর্তমান রুটিন প্রিভিউ</h5>
                    </div>
                    <div class="card-body">
                        <div class="header-section text-center mb-4">
                            <?php if ($logo_image): ?>
                            <div class="text-center mb-3">
                                <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" class="img-fluid" style="max-height: <?php echo $logo_size; ?>px; opacity: <?php echo $logo_opacity; ?>; max-width: 200px; object-fit: contain;">
                            </div>
                            <?php endif; ?>
                            <h2><?php echo !empty($exam_details['custom_institution_name']) ? htmlspecialchars($exam_details['custom_institution_name']) : htmlspecialchars($site_name); ?></h2>
                            <p><?php echo !empty($exam_details['custom_institution_address']) ? htmlspecialchars($exam_details['custom_institution_address']) : htmlspecialchars($site_address); ?></p>
                            <h3 style="color: #007bff; margin-top: 20px;"><?php echo htmlspecialchars($exam_details['name']); ?></h3>
                            <h4>পরীক্ষার রুটিন</h4>
                            <p>
                                <strong>ক্লাস:</strong> <?php echo htmlspecialchars($exam_details['class_name'] . ' - ' . $exam_details['section']); ?> |
                                <strong>সেশন:</strong> <?php echo htmlspecialchars($exam_details['session']); ?>
                                <?php if ($exam_details['group_name']): ?>
                                    | <strong>গ্রুপ:</strong> <?php echo htmlspecialchars($exam_details['group_name']); ?>
                                <?php endif; ?>
                            </p>
                            <?php if (!empty($exam_details['custom_institution_name']) || !empty($exam_details['custom_institution_address'])): ?>
                            <div class="alert alert-info small mt-2">
                                <i class="fas fa-info-circle"></i> 
                                এই রুটিনে কাস্টম প্রতিষ্ঠানের নাম ও ঠিকানা ব্যবহার করা হয়েছে
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!empty($exam_subjects)): ?>
                            <div class="table-responsive">
                                <table class="table table-bordered routine-table">
                                    <thead style="background-color: #007bff; color: white;">
                                        <tr>
                                            <th style="width: 5%;">ক্রমিক</th>
                                            <th style="width: 15%;">তারিখ</th>
                                            <th style="width: 15%;">দিন</th>
                                            <th style="width: 35%;">বিষয়</th>
                                            <th style="width: 30%;">সময়</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $serial = 1; ?>
                                        <?php 
                                        // Group subjects by date
                                        $grouped_by_date = [];
                                        foreach ($exam_subjects as $row) {
                                            $d = date('Y-m-d', strtotime($row['exam_date']));
                                            if (!isset($grouped_by_date[$d])) { $grouped_by_date[$d] = []; }
                                            $grouped_by_date[$d][] = $row;
                                        }
                                        // Preserve order as fetched (already ordered by exam_date, start_time)
                                        $ordered_dates = array_keys($grouped_by_date);
                                        
                                        foreach ($ordered_dates as $dateKey): 
                                            $rows = $grouped_by_date[$dateKey];
                                            // Build subjects string with slash
                                            $subject_parts = [];
                                            $time_parts = [];
                                            foreach ($rows as $r) {
                                                $label = $r['subject_name'] . ($r['subject_code'] ? ' ('.$r['subject_code'].')' : '');
                                                $subject_parts[] = $label;
                                                $time_parts[] = date('h:i A', strtotime($r['start_time'])) . ' - ' . date('h:i A', strtotime($r['end_time']));
                                            }
                                            // Unique values
                                            $time_parts = array_values(array_unique($time_parts));
                                            $date_display = date('d/m/Y', strtotime($dateKey));
                                            $days = [
                                                'Sunday' => 'রবিবার',
                                                'Monday' => 'সোমবার',
                                                'Tuesday' => 'মঙ্গলবার',
                                                'Wednesday' => 'বুধবার',
                                                'Thursday' => 'বৃহস্পতিবার',
                                                'Friday' => 'শুক্রবার',
                                                'Saturday' => 'শনিবার'
                                            ];
                                            $day_display = $days[date('l', strtotime($dateKey))];
                                        ?>
                                            <tr>
                                                <td><?php echo $serial++; ?></td>
                                                <td><?php echo $date_display; ?></td>
                                                <td><?php echo $day_display; ?></td>
                                                <td style="text-align: left; padding-left: 10px;">
                                                    <strong><?php echo implode(' / ', $subject_parts); ?></strong>
                                                </td>
                                                <td><?php echo !empty($time_parts) ? implode(' / ', $time_parts) : '-'; ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-warning text-center">
                                <i class="fas fa-exclamation-triangle"></i> এই পরীক্ষার জন্য কোন বিষয় যোগ করা হয়নি
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>