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

// Permission check
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'] ?? '', ['admin','teacher'])) {
    header('Location: ../login.php');
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $code = strtoupper(trim($_POST['code'] ?? ''));
    $description = trim($_POST['description'] ?? '');

    if ($name === '' || $code === '') {
        $error_message = 'বিষয়ের নাম বা কোড প্রয়োজন';
    } else {
        try {
            // Check duplicate code
            $chk = $pdo->prepare('SELECT COUNT(*) FROM subjects WHERE code = ?');
            $chk->execute([$code]);
            if ($chk->fetchColumn() > 0) {
                $error_message = 'এই কোড ইতিমধ্যে একটি বিষয়ের জন্য ব্যবহৃত হয়েছে';
            } else {
                $stmt = $pdo->prepare('INSERT INTO subjects (name, code, description, status, created_at) VALUES (?, ?, ?, ?, NOW())');
                $stmt->execute([$name, $code, $description, 'active']);
                $success_message = 'বিষয় সফলভাবে যোগ করা হয়েছে';
                // Clear POST values so form is empty after success
                $_POST = [];
            }
        } catch (Exception $e) {
            $error_message = 'বিষয় যোগ করতে সমস্যা হয়েছে: ' . $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="../assets/css/style.css" rel="stylesheet">
    <style>body{padding-bottom:40px}</style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <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="manage.php"><i class="fas fa-cog"></i> বিষয় ব্যবস্থাপনা</a>
                <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-plus"></i> নতুন বিষয় যোগ</h5>
                        <!-- Use absolute path and JS fallback to ensure reliable navigation -->
                        <a href="/bidda/subjects/manage.php" id="backBtn" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-left"></i> ফিরুন
                        </a>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <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" role="alert">
                                <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="">
                            <div class="mb-3">
                                <label class="form-label">বিষয়ের নাম <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($_POST['name'] ?? '', ENT_QUOTES); ?>" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">কোড <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="code" value="<?php echo htmlspecialchars($_POST['code'] ?? '', ENT_QUOTES); ?>" required>
                                <div class="form-text">উদাহরণ: BAN101, ENG101, MATH101</div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">বিবরণ</label>
                                <textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars($_POST['description'] ?? '', ENT_QUOTES); ?></textarea>
                            </div>

                            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> যোগ করুন</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Ensure back button always navigates to manage page (fallback)
        (function(){
            var btn = document.getElementById('backBtn');
            if (!btn) return;
            btn.addEventListener('click', function(e){
                // If something else prevented default, force navigation
                setTimeout(function(){
                    if (document.location.pathname.replace(/\/+$/,'') !== '/bidda/subjects/manage.php') {
                        window.location.href = '/bidda/subjects/manage.php';
                    }
                }, 10);
            });
        })();
    </script>
</body>
</html>
