<?php
/**
 * Siswa (Student) Management Module
 * Koperasi Management System
 */

$pageTitle = 'Data Siswa';
$pageSubtitle = 'Manajemen data siswa penabung';

require_once __DIR__ . '/../config/database.php';
$db = getDB();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $stmt = $db->prepare("INSERT INTO siswa (nis, nama, kelas, alamat, status) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['nis'],
            sanitize($_POST['nama']),
            sanitize($_POST['kelas']),
            sanitize($_POST['alamat']),
            $_POST['status'] ?? 'aktif'
        ]);
        setFlash('success', "Siswa " . $_POST['nama'] . " berhasil ditambahkan.");
        header('Location: index.php');
        exit;
    }
    
    if ($action === 'edit') {
        $stmt = $db->prepare("UPDATE siswa SET nis = ?, nama = ?, kelas = ?, alamat = ?, status = ? WHERE id = ?");
        $stmt->execute([
            $_POST['nis'],
            sanitize($_POST['nama']),
            sanitize($_POST['kelas']),
            sanitize($_POST['alamat']),
            $_POST['status'],
            $_POST['id']
        ]);
        setFlash('success', "Data siswa berhasil diperbarui.");
        header('Location: index.php');
        exit;
    }
    
    if ($action === 'delete') {
        // Transactions will be deleted by CASCADE foreign key
        $stmt = $db->prepare("DELETE FROM siswa WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        setFlash('success', "Siswa berhasil dihapus.");
        header('Location: index.php');
        exit;
    }
}

// Search & Pagination
$search = $_GET['search'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

$where = "";
$params = [];
if ($search) {
    $where = "WHERE nama LIKE ? OR nis LIKE ?";
    $params = ["%$search%", "%$search%"];
}

$countStmt = $db->prepare("SELECT COUNT(*) FROM siswa $where");
$countStmt->execute($params);
$totalRows = $countStmt->fetchColumn();
$totalPages = ceil($totalRows / $perPage);

$stmt = $db->prepare("
    SELECT s.*,
        COALESCE(SUM(CASE WHEN ts.tipe = 'setoran' THEN ts.jumlah ELSE -ts.jumlah END), 0) AS saldo_akhir
    FROM siswa s
    LEFT JOIN tabungan_siswa ts ON ts.siswa_id = s.id
    $where
    GROUP BY s.id
    ORDER BY s.nama ASC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$siswaList = $stmt->fetchAll();

// Edit data
$editData = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM siswa WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editData = $stmt->fetch();
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <div class="toolbar" style="width: 100%;">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" placeholder="Cari siswa (Nama/NIS)..." value="<?= htmlspecialchars($search) ?>"
                       onkeydown="if(event.key==='Enter') { window.location='index.php?search='+this.value; }">
            </div>
            <div style="margin-left: auto; display: flex; gap: 10px;">
                <a href="laporan.php" class="btn btn-info" style="border-radius: 10px;">
                    <i class="fas fa-file-alt"></i> Laporan
                </a>
                <button class="btn btn-primary" onclick="openModal('addSiswaModal')" style="border-radius: 10px;">
                    <i class="fas fa-user-plus"></i> Tambah Siswa
                </button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>NIS</th>
                    <th>Nama Siswa</th>
                    <th>Kelas</th>
                    <th>Alamat</th>
                    <th class="text-end">Saldo Akhir</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($siswaList)): ?>
                    <tr><td colspan="7" class="text-center text-muted" style="padding: 40px;">Tidak ada data siswa</td></tr>
                <?php else: ?>
                    <?php foreach ($siswaList as $s): ?>
                        <tr>
                            <td><code><?= htmlspecialchars($s['nis'] ?: '-') ?></code></td>
                            <td><strong><?= htmlspecialchars($s['nama']) ?></strong></td>
                            <td><?= htmlspecialchars($s['kelas']) ?></td>
                            <td><?= htmlspecialchars($s['alamat'] ?: '-') ?></td>
                            <td class="text-end fw-bold" style="color: <?= $s['saldo_akhir'] > 0 ? 'var(--success-600)' : ($s['saldo_akhir'] < 0 ? 'var(--danger-500)' : 'inherit') ?>">
                                <?= formatRupiah($s['saldo_akhir']) ?>
                            </td>
                            <td>
                                <span class="badge <?= $s['status'] === 'aktif' ? 'badge-success' : 'badge-danger' ?>">
                                    <?= ucfirst($s['status']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="transaksi.php?siswa_id=<?= $s['id'] ?>" class="btn btn-icon btn-outline" title="Lihat Tabungan">
                                        <i class="fas fa-wallet" style="color: var(--primary-500);"></i>
                                    </a>
                                    <a href="index.php?edit=<?= $s['id'] ?>" class="btn btn-icon btn-outline" title="Edit">
                                        <i class="fas fa-pen" style="color: var(--warning-500);"></i>
                                    </a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus siswa ini? Tabungan juga akan dihapus.');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                        <button type="submit" class="btn btn-icon btn-outline" title="Hapus">
                                            <i class="fas fa-trash" style="color: var(--danger-500);"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
        <div class="card-footer">
            <div class="pagination">
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                    <a href="index.php?page=<?= $p ?>&search=<?= urlencode($search) ?>" class="<?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
                <?php endfor; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Add Siswa Modal -->
<div class="modal" id="addSiswaModal">
    <div class="modal-header">
        <h3>Tambah Siswa Baru</h3>
        <button class="modal-close" onclick="closeModal('addSiswaModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
            <div class="form-group">
                <label>NIS</label>
                <input type="text" name="nis" class="form-control" placeholder="Contoh: 2024001">
            </div>
            <div class="form-group">
                <label>Nama Lengkap <span class="required">*</span></label>
                <input type="text" name="nama" class="form-control" required placeholder="Nama siswa">
            </div>
            <div class="form-group">
                <label>Kelas</label>
                <input type="text" name="kelas" class="form-control" placeholder="Contoh: X IPA 1">
            </div>
            <div class="form-group">
                <label>Alamat</label>
                <textarea name="alamat" class="form-control" rows="2" placeholder="Alamat siswa"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addSiswaModal')">Batal</button>
            <button type="submit" class="btn btn-primary">Simpan</button>
        </div>
    </form>
</div>

<!-- Edit Siswa Modal -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editSiswaModal'));</script>
<div class="modal" id="editSiswaModal">
    <div class="modal-header">
        <h3>Edit Data Siswa</h3>
        <button class="modal-close" onclick="window.location='index.php'"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" value="<?= $editData['id'] ?>">
        <div class="modal-body">
            <div class="form-group">
                <label>NIS</label>
                <input type="text" name="nis" class="form-control" value="<?= htmlspecialchars($editData['nis']) ?>">
            </div>
            <div class="form-group">
                <label>Nama Lengkap <span class="required">*</span></label>
                <input type="text" name="nama" class="form-control" required value="<?= htmlspecialchars($editData['nama']) ?>">
            </div>
            <div class="form-group">
                <label>Kelas</label>
                <input type="text" name="kelas" class="form-control" value="<?= htmlspecialchars($editData['kelas']) ?>">
            </div>
            <div class="form-group">
                <label>Alamat</label>
                <textarea name="alamat" class="form-control" rows="2"><?= htmlspecialchars($editData['alamat']) ?></textarea>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select name="status" class="form-control">
                    <option value="aktif" <?= $editData['status'] === 'aktif' ? 'selected' : '' ?>>Aktif</option>
                    <option value="lulus" <?= $editData['status'] === 'lulus' ? 'selected' : '' ?>>Lulus</option>
                    <option value="keluar" <?= $editData['status'] === 'keluar' ? 'selected' : '' ?>>Keluar</option>
                </select>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.location='index.php'">Batal</button>
            <button type="submit" class="btn btn-primary">Perbarui</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php include __DIR__ . '/../includes/footer.php'; ?>
