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

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

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add' || $action == 'edit') {
        $id = $_POST['id'] ?? null;
        $session = $_POST['session'];
        $exam_type = $_POST['exam_type'];
        $class_id = $_POST['class_id'];
        $publish_date = $_POST['publish_date'];
        $expiry_date = $_POST['expiry_date'] ?: null;
        $status = $_POST['status'];
        $remarks = $_POST['remarks'] ?? '';
        
        try {
            if ($action == 'add') {
                $stmt = $pdo->prepare("INSERT INTO result_publications (session, exam_type, class_id, publish_date, expiry_date, status, remarks) 
                                       VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$session, $exam_type, $class_id, $publish_date, $expiry_date, $status, $remarks]);
                $message = "ফলাফল প্রকাশের তথ্য সফলভাবে যোগ করা হয়েছে!";
            } else {
                $stmt = $pdo->prepare("UPDATE result_publications 
                                       SET session = ?, exam_type = ?, class_id = ?, publish_date = ?, expiry_date = ?, status = ?, remarks = ?
                                       WHERE id = ?");
                $stmt->execute([$session, $exam_type, $class_id, $publish_date, $expiry_date, $status, $remarks, $id]);
                $message = "ফলাফল প্রকাশের তথ্য সফলভাবে আপডেট করা হয়েছে!";
            }
        } catch (Exception $e) {
            $error = "একটি সমস্যা হয়েছে: " . $e->getMessage();
        }
    } elseif ($action == 'delete') {
        $id = $_POST['id'];
        try {
            $stmt = $pdo->prepare("DELETE FROM result_publications WHERE id = ?");
            $stmt->execute([$id]);
            $message = "ফলাফল প্রকাশের তথ্য সফলভাবে মুছে ফেলা হয়েছে!";
        } catch (Exception $e) {
            $error = "মুছতে সমস্যা হয়েছে: " . $e->getMessage();
        }
    }
}

// Check if table exists
$tableExists = false;
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'result_publications'");
    $tableExists = ($stmt->rowCount() > 0);
} catch (Exception $e) {
    $error = "টেবিল চেক করতে সমস্যা হয়েছে: " . $e->getMessage();
}

// Create table if not exists
if (!$tableExists) {
    try {
        $pdo->exec("CREATE TABLE result_publications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            session VARCHAR(10) NOT NULL,
            exam_type VARCHAR(50) NOT NULL,
            class_id INT,
            publish_date DATETIME NOT NULL,
            expiry_date DATETIME,
            status ENUM('published', 'scheduled', 'expired', 'hidden') DEFAULT 'scheduled',
            remarks TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_session_exam (session, exam_type),
            INDEX idx_status (status),
            INDEX idx_dates (publish_date, expiry_date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        $message = "ফলাফল প্রকাশের টেবিল সফলভাবে তৈরি করা হয়েছে!";
    } catch (Exception $e) {
        $error = "টেবিল তৈরি করতে সমস্যা হয়েছে: " . $e->getMessage();
    }
}

// Get all publications
$publications = [];
try {
    $stmt = $pdo->query("SELECT rp.*, c.name as class_name, c.section 
                         FROM result_publications rp
                         LEFT JOIN classes c ON rp.class_id = c.id
                         ORDER BY rp.publish_date DESC, rp.session DESC");
    $publications = $stmt->fetchAll();
} catch (Exception $e) {
    $error = "ফলাফল প্রকাশের তথ্য লোড করতে সমস্যা হয়েছে: " . $e->getMessage();
}

// Get classes
$classes = [];
try {
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name");
    $classes = $stmt->fetchAll();
} catch (Exception $e) {
    $error = "ক্লাসের তথ্য লোড করতে সমস্যা হয়েছে: " . $e->getMessage();
}

// Get distinct sessions
$sessions = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC");
    $sessions = $stmt->fetchAll();
} catch (Exception $e) {
    $error = "সেশনের তথ্য লোড করতে সমস্যা হয়েছে: " . $e->getMessage();
}

// Get distinct exam types
$exam_types = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type");
    $exam_types = $stmt->fetchAll();
} catch (Exception $e) {
    $error = "পরীক্ষার ধরনের তথ্য লোড করতে সমস্যা হয়েছে: " . $e->getMessage();
}

// Auto-update status based on dates
$now = date('Y-m-d H:i:s');
try {
    $pdo->exec("UPDATE result_publications 
                SET status = CASE 
                    WHEN publish_date > '$now' THEN 'scheduled'
                    WHEN expiry_date IS NOT NULL AND expiry_date < '$now' THEN 'expired'
                    WHEN publish_date <= '$now' AND (expiry_date IS NULL OR expiry_date >= '$now') THEN 'published'
                END
                WHERE status != 'hidden'");
} catch (Exception $e) {
    $error = "স্ট্যাটাস আপডেট করতে সমস্যা হয়েছে: " . $e->getMessage();
}
?>
<!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="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: #f5f7fa;
        }
        .navbar {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            box-shadow: 0 4px 20px rgba(0, 103, 71, 0.3);
        }
        .page-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            padding: 30px 0;
            margin-bottom: 30px;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 15px 20px;
            font-weight: 600;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        .status-published {
            background: #28a745;
            color: white;
        }
        .status-scheduled {
            background: #ffc107;
            color: #000;
        }
        .status-expired {
            background: #dc3545;
            color: white;
        }
        .status-hidden {
            background: #6c757d;
            color: white;
        }
        .btn-add {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            border: none;
            font-weight: 600;
        }
        .btn-add:hover {
            background: linear-gradient(135deg, #004d35 0%, #006747 100%);
            color: white;
        }
        .date-indicator {
            font-size: 0.9rem;
            color: #666;
        }
        .date-indicator i {
            margin-right: 5px;
        }
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .error-message {
            color: #dc3545;
            font-weight: 500;
            margin-top: 5px;
        }
        .table-responsive {
            border-radius: 0 0 15px 15px;
        }
        .table th {
            background-color: #f0f5f3;
            font-weight: 600;
        }
        .btn-action {
            padding: 5px 10px;
            margin: 0 2px;
        }
        .form-label {
            font-weight: 500;
        }
        .form-control:focus, .form-select:focus {
            border-color: #006747;
            box-shadow: 0 0 0 0.25rem rgba(0, 103, 71, 0.25);
        }
        .alert {
            border-radius: 10px;
            font-weight: 500;
        }
        .modal-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
        }
        .modal-title {
            font-weight: 600;
        }
        .btn-close {
            background-color: white;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-dark">
        <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 text-white" href="admin_dashboard.php">
                    <i class="fas fa-tachometer-alt"></i> ড্যাশবোর্ড
                </a>
                <a class="nav-link text-white" href="index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
            </div>
        </div>
    </nav>

    <!-- Page Header -->
    <div class="page-header">
        <div class="container">
            <h2><i class="fas fa-calendar-check"></i> ফলাফল প্রকাশ ব্যবস্থাপনা</h2>
            <p class="mb-0">ফলাফল প্রকাশ ও মেয়াদ উত্তীর্ণের তারিখ নির্ধারণ করুন</p>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container mb-5">
        <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i> <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>

        <!-- Add New Publication Card -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-plus-circle me-2"></i> নতুন ফলাফল প্রকাশ যোগ করুন</span>
            </div>
            <div class="card-body">
                <form action="" method="POST" id="addPublicationForm">
                    <input type="hidden" name="action" value="add">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="session" class="form-label">সেশন <span class="text-danger">*</span></label>
                            <select class="form-select" name="session" id="session" required>
                                <option value="">সেশন নির্বাচন করুন</option>
                                <?php foreach ($sessions as $session): ?>
                                <option value="<?php echo htmlspecialchars($session['session']); ?>"><?php echo htmlspecialchars($session['session']); ?></option>
                                <?php endforeach; ?>
                                <?php if (empty($sessions)): ?>
                                <option value="2023">2023</option>
                                <option value="2022">2022</option>
                                <option value="2021">2021</option>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="exam_type" class="form-label">পরীক্ষার ধরন <span class="text-danger">*</span></label>
                            <select class="form-select" name="exam_type" id="exam_type" required>
                                <option value="">পরীক্ষার ধরন নির্বাচন করুন</option>
                                <?php foreach ($exam_types as $exam): ?>
                                <option value="<?php echo htmlspecialchars($exam['exam_type']); ?>"><?php echo htmlspecialchars($exam['exam_type']); ?></option>
                                <?php endforeach; ?>
                                <?php if (empty($exam_types)): ?>
                                <option value="মধ্যবার্ষিক পরীক্ষা">মধ্যবার্ষিক পরীক্ষা</option>
                                <option value="বার্ষিক পরীক্ষা">বার্ষিক পরীক্ষা</option>
                                <option value="অর্ধ-বার্ষিক পরীক্ষা">অর্ধ-বার্ষিক পরীক্ষা</option>
                                <option value="নির্বাচনী পরীক্ষা">নির্বাচনী পরীক্ষা</option>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="class_id" class="form-label">শ্রেণি <span class="text-danger">*</span></label>
                            <select class="form-select" name="class_id" id="class_id" required>
                                <option value="">শ্রেণি নির্বাচন করুন</option>
                                <?php foreach ($classes as $class): ?>
                                <option value="<?php echo $class['id']; ?>"><?php echo htmlspecialchars($class['name'] . ' ' . $class['section']); ?></option>
                                <?php endforeach; ?>
                                <?php if (empty($classes)): ?>
                                <option value="1">৬ষ্ঠ শ্রেণি</option>
                                <option value="2">৭ম শ্রেণি</option>
                                <option value="3">৮ম শ্রেণি</option>
                                <option value="4">৯ম শ্রেণি</option>
                                <option value="5">১০ম শ্রেণি</option>
                                <?php endif; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="publish_date" class="form-label">প্রকাশের তারিখ <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control datepicker" name="publish_date" id="publish_date" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="expiry_date" class="form-label">মেয়াদ উত্তীর্ণের তারিখ</label>
                            <input type="datetime-local" class="form-control datepicker" name="expiry_date" id="expiry_date">
                            <small class="text-muted">ফাঁকা রাখলে ফলাফল কখনো মেয়াদ উত্তীর্ণ হবে না</small>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="status" class="form-label">স্ট্যাটাস <span class="text-danger">*</span></label>
                            <select class="form-select" name="status" id="status" required>
                                <option value="scheduled">নির্ধারিত</option>
                                <option value="published">প্রকাশিত</option>
                                <option value="hidden">লুকায়িত</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="remarks" class="form-label">মন্তব্য</label>
                        <textarea class="form-control" name="remarks" id="remarks" rows="2"></textarea>
                    </div>
                    <div class="text-end">
                        <button type="submit" class="btn btn-add">
                            <i class="fas fa-plus-circle me-2"></i> যোগ করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Publications List Card -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-list me-2"></i> ফলাফল প্রকাশের তালিকা</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">সেশন</th>
                                <th scope="col">পরীক্ষার ধরন</th>
                                <th scope="col">শ্রেণি</th>
                                <th scope="col">স্ট্যাটাস</th>
                                <th scope="col">প্রকাশের তারিখ</th>
                                <th scope="col">মেয়াদ উত্তীর্ণের তারিখ</th>
                                <th scope="col">পদক্ষেপ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($publications) > 0): ?>
                                <?php $i = 1; foreach ($publications as $pub): ?>
                                <tr>
                                    <td><?php echo $i++; ?></td>
                                    <td><?php echo htmlspecialchars($pub['session']); ?></td>
                                    <td><?php echo htmlspecialchars($pub['exam_type']); ?></td>
                                    <td><?php echo htmlspecialchars($pub['class_name'] . ' ' . $pub['section']); ?></td>
                                    <td>
                                        <?php 
                                        $statusClass = '';
                                        $statusText = '';
                                        switch($pub['status']) {
                                            case 'published':
                                                $statusClass = 'status-published';
                                                $statusText = 'প্রকাশিত';
                                                break;
                                            case 'scheduled':
                                                $statusClass = 'status-scheduled';
                                                $statusText = 'নির্ধারিত';
                                                break;
                                            case 'expired':
                                                $statusClass = 'status-expired';
                                                $statusText = 'মেয়াদ উত্তীর্ণ';
                                                break;
                                            case 'hidden':
                                                $statusClass = 'status-hidden';
                                                $statusText = 'লুকায়িত';
                                                break;
                                        }
                                        ?>
                                        <span class="status-badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                                    </td>
                                    <td>
                                        <div class="date-indicator">
                                            <i class="far fa-calendar-alt"></i> 
                                            <?php echo date('d/m/Y h:i A', strtotime($pub['publish_date'])); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($pub['expiry_date']): ?>
                                        <div class="date-indicator">
                                            <i class="far fa-calendar-times"></i> 
                                            <?php echo date('d/m/Y h:i A', strtotime($pub['expiry_date'])); ?>
                                        </div>
                                        <?php else: ?>
                                        <span class="text-muted">নির্ধারিত নয়</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-primary btn-action edit-btn" 
                                                data-id="<?php echo $pub['id']; ?>"
                                                data-session="<?php echo htmlspecialchars($pub['session']); ?>"
                                                data-exam-type="<?php echo htmlspecialchars($pub['exam_type']); ?>"
                                                data-class-id="<?php echo $pub['class_id']; ?>"
                                                data-publish-date="<?php echo $pub['publish_date']; ?>"
                                                data-expiry-date="<?php echo $pub['expiry_date']; ?>"
                                                data-status="<?php echo $pub['status']; ?>"
                                                data-remarks="<?php echo htmlspecialchars($pub['remarks']); ?>">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger btn-action delete-btn" 
                                                data-id="<?php echo $pub['id']; ?>"
                                                data-session="<?php echo htmlspecialchars($pub['session']); ?>"
                                                data-exam-type="<?php echo htmlspecialchars($pub['exam_type']); ?>">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center py-4">কোন ফলাফল প্রকাশের তথ্য পাওয়া যায়নি</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel"><i class="fas fa-edit me-2"></i> ফলাফল প্রকাশের তথ্য সম্পাদনা</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="" method="POST" id="editPublicationForm">
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="edit_id">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="edit_session" class="form-label">সেশন <span class="text-danger">*</span></label>
                                <select class="form-select" name="session" id="edit_session" required>
                                    <option value="">সেশন নির্বাচন করুন</option>
                                    <?php foreach ($sessions as $session): ?>
                                    <option value="<?php echo htmlspecialchars($session['session']); ?>"><?php echo htmlspecialchars($session['session']); ?></option>
                                    <?php endforeach; ?>
                                    <?php if (empty($sessions)): ?>
                                    <option value="2023">2023</option>
                                    <option value="2022">2022</option>
                                    <option value="2021">2021</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="edit_exam_type" class="form-label">পরীক্ষার ধরন <span class="text-danger">*</span></label>
                                <select class="form-select" name="exam_type" id="edit_exam_type" required>
                                    <option value="">পরীক্ষার ধরন নির্বাচন করুন</option>
                                    <?php foreach ($exam_types as $exam): ?>
                                    <option value="<?php echo htmlspecialchars($exam['exam_type']); ?>"><?php echo htmlspecialchars($exam['exam_type']); ?></option>
                                    <?php endforeach; ?>
                                    <?php if (empty($exam_types)): ?>
                                    <option value="মধ্যবার্ষিক পরীক্ষা">মধ্যবার্ষিক পরীক্ষা</option>
                                    <option value="বার্ষিক পরীক্ষা">বার্ষিক পরীক্ষা</option>
                                    <option value="অর্ধ-বার্ষিক পরীক্ষা">অর্ধ-বার্ষিক পরীক্ষা</option>
                                    <option value="নির্বাচনী পরীক্ষা">নির্বাচনী পরীক্ষা</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="edit_class_id" class="form-label">শ্রেণি <span class="text-danger">*</span></label>
                                <select class="form-select" name="class_id" id="edit_class_id" required>
                                    <option value="">শ্রেণি নির্বাচন করুন</option>
                                    <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo $class['id']; ?>"><?php echo htmlspecialchars($class['name'] . ' ' . $class['section']); ?></option>
                                    <?php endforeach; ?>
                                    <?php if (empty($classes)): ?>
                                    <option value="1">৬ষ্ঠ শ্রেণি</option>
                                    <option value="2">৭ম শ্রেণি</option>
                                    <option value="3">৮ম শ্রেণি</option>
                                    <option value="4">৯ম শ্রেণি</option>
                                    <option value="5">১০ম শ্রেণি</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="edit_publish_date" class="form-label">প্রকাশের তারিখ <span class="text-danger">*</span></label>
                                <input type="datetime-local" class="form-control datepicker" name="publish_date" id="edit_publish_date" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="edit_expiry_date" class="form-label">মেয়াদ উত্তীর্ণের তারিখ</label>
                                <input type="datetime-local" class="form-control datepicker" name="expiry_date" id="edit_expiry_date">
                                <small class="text-muted">ফাঁকা রাখলে ফলাফল কখনো মেয়াদ উত্তীর্ণ হবে না</small>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="edit_status" class="form-label">স্ট্যাটাস <span class="text-danger">*</span></label>
                                <select class="form-select" name="status" id="edit_status" required>
                                    <option value="scheduled">নির্ধারিত</option>
                                    <option value="published">প্রকাশিত</option>
                                    <option value="expired">মেয়াদ উত্তীর্ণ</option>
                                    <option value="hidden">লুকায়িত</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="edit_remarks" class="form-label">মন্তব্য</label>
                            <textarea class="form-control" name="remarks" id="edit_remarks" rows="2"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="button" class="btn btn-primary" id="updateBtn">আপডেট করুন</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel"><i class="fas fa-trash-alt me-2"></i> নিশ্চিতকরণ</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>আপনি কি নিশ্চিত যে আপনি এই ফলাফল প্রকাশের তথ্য মুছে ফেলতে চান?</p>
                    <p><strong>সেশন:</strong> <span id="delete_session"></span></p>
                    <p><strong>পরীক্ষার ধরন:</strong> <span id="delete_exam_type"></span></p>
                    <form action="" method="POST" id="deletePublicationForm">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" id="delete_id">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">মুছে ফেলুন</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white text-center py-3 mt-5">
        <div class="container">
            <p class="mb-0">&copy; <?php echo date('Y'); ?> বিদ্যা নিকেতন উচ্চ বিদ্যালয়। সর্বস্বত্ব সংরক্ষিত।</p>
        </div>
    </footer>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize date pickers
            flatpickr(".datepicker", {
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true
            });

            // Edit button click handler
            document.querySelectorAll('.edit-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const session = this.getAttribute('data-session');
                    const examType = this.getAttribute('data-exam-type');
                    const classId = this.getAttribute('data-class-id');
                    const publishDate = this.getAttribute('data-publish-date');
                    const expiryDate = this.getAttribute('data-expiry-date');
                    const status = this.getAttribute('data-status');
                    const remarks = this.getAttribute('data-remarks');

                    document.getElementById('edit_id').value = id;
                    
                    // Set select values
                    const sessionSelect = document.getElementById('edit_session');
                    for (let i = 0; i < sessionSelect.options.length; i++) {
                        if (sessionSelect.options[i].value === session) {
                            sessionSelect.selectedIndex = i;
                            break;
                        }
                    }
                    
                    const examTypeSelect = document.getElementById('edit_exam_type');
                    for (let i = 0; i < examTypeSelect.options.length; i++) {
                        if (examTypeSelect.options[i].value === examType) {
                            examTypeSelect.selectedIndex = i;
                            break;
                        }
                    }
                    
                    const classIdSelect = document.getElementById('edit_class_id');
                    for (let i = 0; i < classIdSelect.options.length; i++) {
                        if (classIdSelect.options[i].value === classId) {
                            classIdSelect.selectedIndex = i;
                            break;
                        }
                    }
                    
                    const statusSelect = document.getElementById('edit_status');
                    for (let i = 0; i < statusSelect.options.length; i++) {
                        if (statusSelect.options[i].value === status) {
                            statusSelect.selectedIndex = i;
                            break;
                        }
                    }
                    
                    // Format datetime for input
                    document.getElementById('edit_publish_date').value = formatDateTimeForInput(publishDate);
                    if (expiryDate) {
                        document.getElementById('edit_expiry_date').value = formatDateTimeForInput(expiryDate);
                    } else {
                        document.getElementById('edit_expiry_date').value = '';
                    }
                    
                    document.getElementById('edit_remarks').value = remarks;
                    
                    const editModal = new bootstrap.Modal(document.getElementById('editModal'));
                    editModal.show();
                });
            });

            // Delete button click handler
            document.querySelectorAll('.delete-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const session = this.getAttribute('data-session');
                    const examType = this.getAttribute('data-exam-type');
                    
                    document.getElementById('delete_id').value = id;
                    document.getElementById('delete_session').textContent = session;
                    document.getElementById('delete_exam_type').textContent = examType;
                    
                    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
                    deleteModal.show();
                });
            });

            // Update button click handler
            document.getElementById('updateBtn').addEventListener('click', function() {
                document.getElementById('editPublicationForm').submit();
            });

            // Confirm delete button click handler
            document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
                document.getElementById('deletePublicationForm').submit();
            });

            // Helper function to format datetime for input
            function formatDateTimeForInput(dateTimeStr) {
                const dt = new Date(dateTimeStr);
                return dt.getFullYear() + '-' + 
                       String(dt.getMonth() + 1).padStart(2, '0') + '-' + 
                       String(dt.getDate()).padStart(2, '0') + 'T' + 
                       String(dt.getHours()).padStart(2, '0') + ':' + 
                       String(dt.getMinutes()).padStart(2, '0');
            }
        });
    </script>
</body>
</html>