<?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 siswa
if (isset($_POST['tambah_siswa'])) {
    $nis = $conn->real_escape_string($_POST['nis']);
    $nama = $conn->real_escape_string($_POST['nama']);
    $kelas = $conn->real_escape_string($_POST['kelas']);
    
    $sql = "INSERT INTO ujn_siswa (nis, nama, kelas) VALUES ('$nis', '$nama', '$kelas')";
    if ($conn->query($sql)) {
        $success = "Siswa berhasil ditambahkan";
    } else {
        $error = "Gagal menambahkan siswa: " . $conn->error;
    }
}

// Proses edit siswa
if (isset($_POST['edit_siswa'])) {
    $id = $conn->real_escape_string($_POST['id']);
    $nis = $conn->real_escape_string($_POST['nis']);
    $nama = $conn->real_escape_string($_POST['nama']);
    $kelas = $conn->real_escape_string($_POST['kelas']);
    
    $sql = "UPDATE ujn_siswa SET nis = '$nis', nama = '$nama', kelas = '$kelas' WHERE id = '$id'";
    if ($conn->query($sql)) {
        $success = "Siswa berhasil diupdate";
    } else {
        $error = "Gagal mengupdate siswa: " . $conn->error;
    }
}

// Proses hapus siswa
if (isset($_GET['hapus'])) {
    $nis = $conn->real_escape_string($_GET['hapus']);
    $sql = "DELETE FROM ujn_siswa WHERE nis = '$nis'";
    if ($conn->query($sql)) {
        $success = "Siswa berhasil dihapus";
    } else {
        $error = "Gagal menghapus siswa: " . $conn->error;
    }
}

// Proses import siswa
if (isset($_POST['import_siswa'])) {
    if (isset($_FILES['file_import']) && $_FILES['file_import']['error'] == 0) {
        $file = $_FILES['file_import']['tmp_name'];
        $ekstensi = pathinfo($_FILES['file_import']['name'], PATHINFO_EXTENSION);
        
        if ($ekstensi == 'csv') {
            $handle = fopen($file, 'r');
            $success_count = 0;
            $error_count = 0;
            $errors = [];
            
            // Skip header
            fgetcsv($handle, 1000, ",");
            
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if (count($data) == 3) {
                    $nis = $conn->real_escape_string(trim($data[0]));
                    $nama = $conn->real_escape_string(trim($data[1]));
                    $kelas = $conn->real_escape_string(trim($data[2]));
                    
                    // Cek apakah NIS sudah ada
                    $cek_sql = "SELECT id FROM ujn_siswa WHERE nis = '$nis'";
                    $cek_result = $conn->query($cek_sql);
                    
                    if ($cek_result->num_rows > 0) {
                        // Update data yang sudah ada
                        $update_sql = "UPDATE ujn_siswa SET nama = '$nama', kelas = '$kelas' WHERE nis = '$nis'";
                        if ($conn->query($update_sql)) {
                            $success_count++;
                        } else {
                            $error_count++;
                            $errors[] = "Gagal update siswa NIS: $nis - " . $conn->error;
                        }
                    } else {
                        // Insert data baru
                        $insert_sql = "INSERT INTO ujn_siswa (nis, nama, kelas) VALUES ('$nis', '$nama', '$kelas')";
                        if ($conn->query($insert_sql)) {
                            $success_count++;
                        } else {
                            $error_count++;
                            $errors[] = "Gagal insert siswa NIS: $nis - " . $conn->error;
                        }
                    }
                }
            }
            fclose($handle);
            
            if ($error_count == 0) {
                $success = "Import berhasil! $success_count data siswa telah diproses.";
            } else {
                $error = "Import selesai dengan $error_count error. $success_count data berhasil diproses.";
                if (count($errors) > 0) {
                    $error .= "<br>Error detail: " . implode("<br>", array_slice($errors, 0, 5));
                    if (count($errors) > 5) {
                        $error .= "<br>... dan " . (count($errors) - 5) . " error lainnya";
                    }
                }
            }
        } else {
            $error = "Format file harus CSV!";
        }
    } else {
        $error = "Silakan pilih file CSV untuk diimport!";
    }
}

// Ambil data untuk edit
$edit_data = null;
if (isset($_GET['edit'])) {
    $id = $conn->real_escape_string($_GET['edit']);
    $sql = "SELECT * FROM ujn_siswa WHERE id = '$id'";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $edit_data = $result->fetch_assoc();
    }
}

// Konfigurasi pagination dan pencarian
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Query untuk data siswa dengan pencarian
$where = "";
if (!empty($search)) {
    $where = "WHERE nis LIKE '%$search%' OR nama LIKE '%$search%' OR kelas LIKE '%$search%'";
}

$sql = "SELECT * FROM ujn_siswa $where ORDER BY kelas, nama LIMIT $limit OFFSET $offset";
$result = $conn->query($sql);

// Query untuk total data
$sql_total = "SELECT COUNT(*) as total FROM ujn_siswa $where";
$result_total = $conn->query($sql_total);
$total_data = $result_total->fetch_assoc()['total'];
$total_pages = ceil($total_data / $limit);

// Validasi page number
if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
    $offset = ($page - 1) * $limit;
    // Re-query dengan page yang valid
    $sql = "SELECT * FROM ujn_siswa $where ORDER BY kelas, nama LIMIT $limit OFFSET $offset";
    $result = $conn->query($sql);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Siswa - 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;
        }
        .pagination .page-link {
            color: #495057;
        }
        .pagination .page-item.active .page-link {
            background-color: #007bff;
            border-color: #007bff;
        }
    </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 Siswa</p>
        </div>

        <h2 class="mb-4"><i class="fas fa-users me-2"></i>Kelola Data Siswa</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-user-plus' ?> me-2"></i>
                            <?= $edit_data ? 'Edit Siswa' : 'Tambah Siswa' ?>
                        </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">NIS</label>
                                <input type="text" class="form-control" name="nis" 
                                       value="<?= $edit_data ? $edit_data['nis'] : '' ?>" 
                                       required placeholder="Masukkan NIS">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Nama Siswa</label>
                                <input type="text" class="form-control" name="nama"
                                       value="<?= $edit_data ? $edit_data['nama'] : '' ?>" 
                                       required placeholder="Masukkan nama lengkap">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Kelas</label>
                                <input type="text" class="form-control" name="kelas"
                                       value="<?= $edit_data ? $edit_data['kelas'] : '' ?>" 
                                       required placeholder="Contoh: XII IPA 1">
                            </div>
                            
                            <div class="d-grid gap-2">
                                <?php if ($edit_data): ?>
                                    <button type="submit" name="edit_siswa" class="btn btn-warning">
                                        <i class="fas fa-save me-2"></i>Update Siswa
                                    </button>
                                    <a href="kelola_siswa.php" class="btn btn-secondary">
                                        <i class="fas fa-times me-2"></i>Batal
                                    </a>
                                <?php else: ?>
                                    <button type="submit" name="tambah_siswa" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>Simpan Siswa
                                    </button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Card Import Siswa -->
                <div class="card mt-4">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0"><i class="fas fa-file-import me-2"></i>Import Data Siswa</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">File CSV</label>
                                <input type="file" class="form-control" name="file_import" accept=".csv" required>
                                <div class="form-text">
                                    Format CSV: NIS, Nama, Kelas. <a href="javascript:void(0)" onclick="downloadTemplate()">Download template</a>
                                </div>
                            </div>
                            <div class="d-grid">
                                <button type="submit" name="import_siswa" class="btn btn-info">
                                    <i class="fas fa-upload me-2"></i>Import Data
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-list me-2"></i>Daftar Siswa</h5>
                        <div class="d-flex">
                            <!-- Form Pencarian -->
                            <form method="GET" class="me-2">
                                <div class="input-group">
                                    <input type="text" class="form-control" name="search" placeholder="Cari siswa..." value="<?= htmlspecialchars($search) ?>">
                                    <input type="hidden" name="limit" value="<?= $limit ?>">
                                    <button class="btn btn-light" type="submit">
                                        <i class="fas fa-search"></i>
                                    </button>
                                    <?php if (!empty($search)): ?>
                                        <a href="kelola_siswa.php" class="btn btn-outline-light">
                                            <i class="fas fa-times"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Info Jumlah Data -->
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                Menampilkan <?= ($total_data > 0) ? (($page-1)*$limit + 1) : 0 ?> - 
                                <?= min($page * $limit, $total_data) ?> dari <?= $total_data ?> data
                            </div>
                            <!-- Form Limit Data -->
                            <form method="GET" class="d-flex">
                                <?php if (!empty($search)): ?>
                                    <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
                                <?php endif; ?>
                                <select class="form-select form-select-sm" name="limit" onchange="this.form.submit()">
                                    <option value="10" <?= $limit == 10 ? 'selected' : '' ?>>10</option>
                                    <option value="30" <?= $limit == 30 ? 'selected' : '' ?>>30</option>
                                    <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50</option>
                                    <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                                    <option value="<?= $total_data ?>" <?= $limit == $total_data ? 'selected' : '' ?>>All</option>
                                </select>
                            </form>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>NIS</th>
                                        <th>Nama</th>
                                        <th>Kelas</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $no = ($page - 1) * $limit + 1;
                                    
                                    if ($result && $result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            echo "<tr>
                                                    <td>{$no}</td>
                                                    <td><strong>{$row['nis']}</strong></td>
                                                    <td>{$row['nama']}</td>
                                                    <td><span class='badge bg-secondary'>{$row['kelas']}</span></td>
                                                    <td>
                                                        <a href='kelola_siswa.php?edit={$row['id']}&search=" . urlencode($search) . "&limit=$limit&page=$page' class='btn btn-sm btn-warning btn-action' title='Edit Siswa'>
                                                            <i class='fas fa-edit'></i>
                                                        </a>
                                                        <a href='kelola_siswa.php?hapus={$row['nis']}&search=" . urlencode($search) . "&limit=$limit&page=$page' class='btn btn-sm btn-danger btn-action' 
                                                           onclick='return confirm(\"Yakin hapus siswa {$row['nama']}?\")' title='Hapus Siswa'>
                                                            <i class='fas fa-trash'></i>
                                                        </a>
                                                    </td>
                                                </tr>";
                                            $no++;
                                        }
                                    } else {
                                        echo "<tr>
                                                <td colspan='5' class='text-center py-4'>
                                                    <i class='fas fa-users fa-2x text-muted mb-3'></i><br>
                                                    <span class='text-muted'>" . (empty($search) ? 'Tidak ada data siswa' : 'Data tidak ditemukan') . "</span>
                                                </td>
                                            </tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= $page-1 ?>&limit=<?= $limit ?>&search=<?= urlencode($search) ?>">Previous</a>
                                </li>
                                
                                <?php
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                if ($start_page > 1) {
                                    echo '<li class="page-item"><a class="page-link" href="?page=1&limit='.$limit.'&search='.urlencode($search).'">1</a></li>';
                                    if ($start_page > 2) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                }
                                
                                for ($i = $start_page; $i <= $end_page; $i++) {
                                    $active = $i == $page ? 'active' : '';
                                    echo '<li class="page-item '.$active.'"><a class="page-link" href="?page='.$i.'&limit='.$limit.'&search='.urlencode($search).'">'.$i.'</a></li>';
                                }
                                
                                if ($end_page < $total_pages) {
                                    if ($end_page < $total_pages - 1) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'&limit='.$limit.'&search='.urlencode($search).'">'.$total_pages.'</a></li>';
                                }
                                ?>
                                
                                <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= $page+1 ?>&limit=<?= $limit ?>&search=<?= urlencode($search) ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Focus pada input pertama
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('input[name="nis"]').focus();
        });

        // Fungsi untuk download template CSV
        function downloadTemplate() {
            const csvContent = "NIS,Nama,Kelas\n2024001,Ahmad Rizki,XII IPA 1\n2024002,Siti Nurhaliza,XII IPA 1\n2024003,Budi Santoso,XII IPA 2";
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.setAttribute('hidden', '');
            a.setAttribute('href', url);
            a.setAttribute('download', 'template_siswa.csv');
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>
</body>
</html>
<?php $conn->close(); ?>