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

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

// Get all exams for display
$stmt = $pdo->prepare("SELECT * FROM exams ORDER BY exam_date DESC");
$stmt->execute();
$routines = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle deletion if requested
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_id'])) {
    try {
        $routine_id = (int)$_POST['delete_id'];
        $force_delete = isset($_POST['force_delete']) ? true : false;
        
        $pdo->beginTransaction();
        
        if ($force_delete) {
            // Force delete - disable foreign key checks temporarily
            $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
            
            try {
                // Aggressive cleanup of all related tables
                $tables_to_clean = [
                    'exam_attendance',
                    'exam_room_duties',
                    'exam_rooms',
                    'exam_subjects',
                    'results'
                ];
                
                foreach ($tables_to_clean as $table) {
                    $stmt = $pdo->prepare("DELETE FROM `$table` WHERE exam_id = ?");
                    $stmt->execute([$routine_id]);
                }
                
                // Finally delete the exam
                $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
                $stmt->execute([$routine_id]);
                
                // Re-enable foreign key checks
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                
                $pdo->commit();
                $message = 'পরীক্ষার রুটিন জোর করে মুছে ফেলা হয়েছে!';
                $message_type = 'success';
            } catch (Exception $e) {
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                throw $e;
            }
        } else {
            // Normal delete
            // Delete results first (due to foreign key constraints)
            $stmt = $pdo->prepare("DELETE FROM results WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            
            // Delete exam subjects
            $stmt = $pdo->prepare("DELETE FROM exam_subjects WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            
            // Delete the exam routine itself
            $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
            $stmt->execute([$routine_id]);
            
            $pdo->commit();
            $message = 'পরীক্ষার রুটিন সফলভাবে মুছে ফেলা হয়েছে!';
            $message_type = 'success';
        }
    } catch (Exception $e) {
        $pdo->rollBack();
        $message = 'মুছে ফেলতে ত্রুটি: ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>

<!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://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;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <h2 class="mb-4">পরীক্ষার রুটিন মুছুন</h2>
                
                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type == 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if (empty($routines)): ?>
                    <div class="alert alert-info">
                        কোন পরীক্ষার রুটিন পাওয়া যায়নি।
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>নাম</th>
                                    <th>তারিখ</th>
                                    <th>অ্যাকশন</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($routines as $routine): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($routine['name']); ?></td>
                                        <td><?php echo htmlspecialchars($routine['exam_date']); ?></td>
                                        <td>
                                            <form method="POST" style="display: inline;" onsubmit="return confirm('আপনি কি নিশ্চিত যে \"<?php echo htmlspecialchars($routine['name']); ?>\" পরীক্ষার রুটিনটি মুছে ফেলতে চান?');">
                                                <input type="hidden" name="delete_id" value="<?php echo $routine['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-danger">
                                                    <i class="fas fa-trash"></i> মুছুন
                                                </button>
                                            </form>
                                            
                                            <form method="POST" style="display: inline;" onsubmit="return confirm('আপনি কি নিশ্চিত যে \"<?php echo htmlspecialchars($routine['name']); ?>\" পরীক্ষার রুটিনটি জোর করে মুছে ফেলতে চান? এটি সমস্ত সম্পর্কিত ডেটা মুছে ফেলবে।');">
                                                <input type="hidden" name="delete_id" value="<?php echo $routine['id']; ?>">
                                                <input type="hidden" name="force_delete" value="1">
                                                <button type="submit" class="btn btn-sm btn-warning">
                                                    <i class="fas fa-bolt"></i> জোর মুছুন
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
                
                <div class="mt-4">
                    <a href="routine.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> রুটিন পেজে ফিরে যান
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Font Awesome for icons -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
