<?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 = '';
$subject_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($subject_id <= 0) {
    header('Location: list.php');
    exit();
}

// Fetch subject
$stmt = $pdo->prepare("SELECT * FROM subjects WHERE id = ?");
$stmt->execute([$subject_id]);
$subject = $stmt->fetch();
if (!$subject) {
    header('Location: list.php');
    exit();
}

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

    if ($name === '' || $code === '') {
        $error_message = 'বিষয়ের নাম এবং কোড প্রয়োজন';
    } else {
        try {
            // Ensure unique code (excluding current)
            $chk = $pdo->prepare('SELECT COUNT(*) FROM subjects WHERE code = ? AND id != ?');
            $chk->execute([$code, $subject_id]);
            if ($chk->fetchColumn() > 0) {
                throw new Exception('এই কোড দিয়ে ইতিমধ্যে একটি বিষয় রয়েছে');
            }

            $stmt = $pdo->prepare('UPDATE subjects SET name = ?, code = ?, description = ?, status = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$name, $code, $description, $status, $subject_id]);
            $success_message = 'বিষয় সফলভাবে আপডেট হয়েছে';

            // Refresh data
            $stmt = $pdo->prepare('SELECT * FROM subjects WHERE id = ?');
            $stmt->execute([$subject_id]);
            $subject = $stmt->fetch();
        } 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">
</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="list.php"><i class="fas fa-list"></i> বিষয় তালিকা</a>
                <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid 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-edit"></i> বিষয় সম্পাদনা</h5>
                        <div>
                            <a href="list.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> তালিকায় ফিরুন</a>
                        </div>
                    </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">
                            <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($subject['name']); ?>" 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($subject['code']); ?>" required>
                                <div class="form-text">উদাহরণ: BAN101, ENG101</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">বিবরণ</label>
                                <textarea class="form-control" rows="3" name="description"><?php echo htmlspecialchars($subject['description'] ?? ''); ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">অবস্থা</label>
                                <select class="form-select" name="status">
                                    <option value="active" <?php echo ($subject['status'] === 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                                    <option value="inactive" <?php echo ($subject['status'] === 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                </select>
                            </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>
</body>
</html>