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

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$current_user = $_SESSION['user'];

// Proses tambah mata pelajaran
if (isset($_POST['tambah_mapel'])) {
    $kode_mapel = $conn->real_escape_string($_POST['kode_mapel']);
    $nama_mapel = $conn->real_escape_string($_POST['nama_mapel']);
    
    $sql = "INSERT INTO ujn_mata_pelajaran (kode_mapel, nama_mapel) VALUES ('$kode_mapel', '$nama_mapel')";
    if ($conn->query($sql)) {
        $success = "Mata pelajaran berhasil ditambahkan";
    } else {
        $error = "Gagal menambahkan mata pelajaran: " . $conn->error;
    }
}

// Proses edit mata pelajaran
if (isset($_POST['edit_mapel'])) {
    $id = $conn->real_escape_string($_POST['id']);
    $kode_mapel = $conn->real_escape_string($_POST['kode_mapel']);
    $nama_mapel = $conn->real_escape_string($_POST['nama_mapel']);
    
    $sql = "UPDATE ujn_mata_pelajaran SET kode_mapel = '$kode_mapel', nama_mapel = '$nama_mapel' WHERE id = '$id'";
    if ($conn->query($sql)) {
        $success = "Mata pelajaran berhasil diupdate";
    } else {
        $error = "Gagal mengupdate mata pelajaran: " . $conn->error;
    }
}

// Proses hapus mata pelajaran
if (isset($_GET['hapus'])) {
    $id = $conn->real_escape_string($_GET['hapus']);
    
    // Cek apakah mata pelajaran sudah digunakan di kehadiran
    $check_sql = "SELECT COUNT(*) as total FROM ujn_kehadiran WHERE kode_mapel = (SELECT kode_mapel FROM ujn_mata_pelajaran WHERE id = '$id')";
    $check_result = $conn->query($check_sql);
    $check_data = $check_result->fetch_assoc();
    
    if ($check_data['total'] > 0) {
        $error = "Tidak dapat menghapus mata pelajaran karena sudah digunakan dalam data kehadiran";
    } else {
        $sql = "DELETE FROM ujn_mata_pelajaran WHERE id = '$id'";
        if ($conn->query($sql)) {
            $success = "Mata pelajaran berhasil dihapus";
        } else {
            $error = "Gagal menghapus mata pelajaran: " . $conn->error;
        }
    }
}

// Ambil data untuk edit
$edit_data = null;
if (isset($_GET['edit'])) {
    $id = $conn->real_escape_string($_GET['edit']);
    $sql = "SELECT * FROM ujn_mata_pelajaran WHERE id = '$id'";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $edit_data = $result->fetch_assoc();
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Mata Pelajaran - Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .navbar-brand {
            font-weight: bold;
        }
        .card {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        .user-info {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }
        .table th {
            background: #343a40;
            color: white;
            border: none;
            font-weight: 600;
        }
        .btn-action {
            margin: 2px;
        }
        .stats-card {
            color: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            margin-bottom: 20px;
        }
        .stats-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stats-label {
            font-size: 0.8rem;
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-tachometer-alt me-2"></i>Admin Dashboard
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="dashboard.php">
                            <i class="fas fa-home me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="mata_pelajaran.php">
                            <i class="fas fa-database me-1"></i>Kelola Mata Pelajaran
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="kelola_siswa.php">
                            <i class="fas fa-users me-1"></i>Kelola Siswa
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="generate_qr.php">
                            <i class="fas fa-qrcode me-1"></i>Generate QR
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../logout.php">
                            <i class="fas fa-sign-out-alt me-1"></i>Logout
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Info Pengguna -->
        <div class="user-info">
            <h5><i class="fas fa-user-shield me-2"></i>Selamat Datang, <?= htmlspecialchars($current_user['nama_lengkap']); ?></h5>
            <p class="mb-0">Anda login sebagai <strong>Administrator</strong> - Halaman Kelola Mata Pelajaran</p>
        </div>

        <!-- Statistik -->
        <div class="row">
            <div class="col-md-4">
                <div class="stats-card stats-primary">
                    <div class="stats-number">
                        <?php
                        $total_mapel = $conn->query("SELECT COUNT(*) as total FROM ujn_mata_pelajaran")->fetch_assoc()['total'];
                        echo $total_mapel;
                        ?>
                    </div>
                    <div class="stats-label">Total Mata Pelajaran</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card" style="background: linear-gradient(135deg, #28a745, #20c997);">
                    <div class="stats-number">
                        <?php
                        $total_used = $conn->query("SELECT COUNT(DISTINCT kode_mapel) as total FROM ujn_kehadiran")->fetch_assoc()['total'];
                        echo $total_used;
                        ?>
                    </div>
                    <div class="stats-label">Mapel Terpakai</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card" style="background: linear-gradient(135deg, #ffc107, #fd7e14);">
                    <div class="stats-number">
                        <?php
                        $total_unused = $total_mapel - $total_used;
                        echo $total_unused;
                        ?>
                    </div>
                    <div class="stats-label">Mapel Belum Terpakai</div>
                </div>
            </div>
        </div>

        <h2 class="mb-4"><i class="fas fa-book me-2"></i>Kelola Mata Pelajaran</h2>
        
        <?php if (isset($success)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i><?= $success ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-triangle me-2"></i><?= $error ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">
                            <i class="fas <?= $edit_data ? 'fa-edit' : 'fa-plus' ?> me-2"></i>
                            <?= $edit_data ? 'Edit Mata Pelajaran' : 'Tambah Mata Pelajaran' ?>
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <?php if ($edit_data): ?>
                                <input type="hidden" name="id" value="<?= $edit_data['id'] ?>">
                            <?php endif; ?>
                            
                            <div class="mb-3">
                                <label class="form-label">Kode Mata Pelajaran</label>
                                <input type="text" class="form-control" name="kode_mapel" 
                                       value="<?= $edit_data ? $edit_data['kode_mapel'] : '' ?>" 
                                       required placeholder="Contoh: MAT, BIO, FIS"
                                       maxlength="10">
                                <div class="form-text">Maksimal 10 karakter</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Nama Mata Pelajaran</label>
                                <input type="text" class="form-control" name="nama_mapel" 
                                       value="<?= $edit_data ? $edit_data['nama_mapel'] : '' ?>" 
                                       required placeholder="Contoh: Matematika, Biologi"
                                       maxlength="100">
                                <div class="form-text">Maksimal 100 karakter</div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <?php if ($edit_data): ?>
                                    <button type="submit" name="edit_mapel" class="btn btn-warning">
                                        <i class="fas fa-save me-2"></i>Update Mata Pelajaran
                                    </button>
                                    <a href="mata_pelajaran.php" class="btn btn-secondary">
                                        <i class="fas fa-times me-2"></i>Batal
                                    </a>
                                <?php else: ?>
                                    <button type="submit" name="tambah_mapel" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>Simpan Mata Pelajaran
                                    </button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-list me-2"></i>Daftar Mata Pelajaran</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Kode</th>
                                        <th>Nama Mata Pelajaran</th>
                                        <th>Status</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sql = "SELECT mp.*, 
                                                   (SELECT COUNT(*) FROM ujn_kehadiran WHERE kode_mapel = mp.kode_mapel) as digunakan
                                            FROM ujn_mata_pelajaran mp 
                                            ORDER BY mp.nama_mapel";
                                    $result = $conn->query($sql);
                                    $no = 1;
                                    
                                    if ($result && $result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            $status_badge = $row['digunakan'] > 0 ? 
                                                '<span class="badge bg-success">Terpakai</span>' : 
                                                '<span class="badge bg-secondary">Belum Terpakai</span>';
                                            
                                            echo "<tr>
                                                    <td>{$no}</td>
                                                    <td><strong>{$row['kode_mapel']}</strong></td>
                                                    <td>{$row['nama_mapel']}</td>
                                                    <td>{$status_badge}</td>
                                                    <td>
                                                        <a href='mata_pelajaran.php?edit={$row['id']}' class='btn btn-sm btn-warning btn-action' title='Edit'>
                                                            <i class='fas fa-edit'></i>
                                                        </a>";
                                            
                                            // Hanya bisa hapus jika belum digunakan
                                            if ($row['digunakan'] == 0) {
                                                echo "<a href='mata_pelajaran.php?hapus={$row['id']}' class='btn btn-sm btn-danger btn-action' 
                                                       onclick='return confirm(\"Yakin hapus mata pelajaran {$row['nama_mapel']}?\")' title='Hapus'>
                                                        <i class='fas fa-trash'></i>
                                                      </a>";
                                            } else {
                                                echo "<button class='btn btn-sm btn-secondary btn-action' disabled title='Tidak dapat dihapus (sudah terpakai)'>
                                                        <i class='fas fa-trash'></i>
                                                      </button>";
                                            }
                                            
                                            echo "</td>
                                                </tr>";
                                            $no++;
                                        }
                                    } else {
                                        echo "<tr>
                                                <td colspan='5' class='text-center py-4'>
                                                    <i class='fas fa-book fa-2x text-muted mb-3'></i><br>
                                                    <span class='text-muted'>Tidak ada data mata pelajaran</span>
                                                </td>
                                            </tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto capitalisasi untuk kode mapel
        document.querySelector('input[name="kode_mapel"]').addEventListener('input', function(e) {
            this.value = this.value.toUpperCase();
        });

        // Konfirmasi sebelum menghapus
        function confirmDelete(nama) {
            return confirm('Yakin menghapus mata pelajaran ' + nama + '?');
        }

        // Focus pada input pertama
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('input[name="kode_mapel"]').focus();
        });
    </script>
</body>
</html>
<?php $conn->close(); ?>