<?php
/**
 * Tabungan Siswa Transactions Module
 * Koperasi Management System
 */

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

$siswaId = $_GET['siswa_id'] ?? null;
if (!$siswaId) {
    header('Location: index.php');
    exit;
}

// Get student info
$siswaStmt = $db->prepare("SELECT * FROM siswa WHERE id = ?");
$siswaStmt->execute([$siswaId]);
$siswa = $siswaStmt->fetch();

if (!$siswa) {
    setFlash('danger', 'Data siswa tidak ditemukan.');
    header('Location: index.php');
    exit;
}

$pageTitle = 'Tabungan: ' . htmlspecialchars($siswa['nama']);
$pageSubtitle = ($siswa['nis'] ? 'NIS: ' . htmlspecialchars($siswa['nis']) . ' - ' : '') . 'Kelas: ' . htmlspecialchars($siswa['kelas']);

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $stmt = $db->prepare("INSERT INTO tabungan_siswa (siswa_id, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $siswaId,
            $_POST['tipe'],
            str_replace('.', '', $_POST['jumlah']),
            $_POST['tanggal'],
            sanitize($_POST['keterangan'] ?? ''),
            $_SESSION['user_id']
        ]);
        setFlash('success', 'Transaksi tabungan berhasil dicatat.');
        header('Location: transaksi.php?siswa_id=' . $siswaId);
        exit;
    }
    
    if ($action === 'edit') {
        $stmt = $db->prepare("UPDATE tabungan_siswa SET tipe = ?, jumlah = ?, tanggal = ?, keterangan = ? WHERE id = ?");
        $stmt->execute([
            $_POST['tipe'],
            str_replace('.', '', $_POST['jumlah']),
            $_POST['tanggal'],
            sanitize($_POST['keterangan'] ?? ''),
            $_POST['id']
        ]);
        setFlash('success', 'Transaksi berhasil diperbarui.');
        header('Location: transaksi.php?siswa_id=' . $siswaId);
        exit;
    }
    
    if ($action === 'delete') {
        $stmt = $db->prepare("DELETE FROM tabungan_siswa WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Transaksi berhasil dihapus.');
        header('Location: transaksi.php?siswa_id=' . $siswaId);
        exit;
    }
}

// Calculate Current Balance
$balanceStmt = $db->prepare("
    SELECT 
        SUM(CASE WHEN tipe = 'setoran' THEN jumlah ELSE -jumlah END) as saldo 
    FROM tabungan_siswa 
    WHERE siswa_id = ?
");
$balanceStmt->execute([$siswaId]);
$saldo = $balanceStmt->fetchColumn() ?: 0;

// Transactions List
$stmt = $db->prepare("SELECT ts.*, u.username as admin_name FROM tabungan_siswa ts LEFT JOIN users u ON ts.created_by = u.id WHERE ts.siswa_id = ? ORDER BY ts.tanggal DESC, ts.created_at DESC");
$stmt->execute([$siswaId]);
$transaksiList = $stmt->fetchAll();

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

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

<div class="row mb-4">
    <div class="col-md-4">
        <div class="card stat-card" style="background: linear-gradient(135deg, var(--primary-600), var(--primary-400)); color: white;">
            <div class="stat-icon" style="background: rgba(255,255,255,0.2);"><i class="fas fa-wallet"></i></div>
            <div class="stat-details">
                <div class="stat-label" style="color: rgba(255,255,255,0.8);">Saldo Saat Ini</div>
                <div class="stat-value" style="font-size: 24px;"><?= formatRupiah($saldo) ?></div>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="toolbar" style="width: 100%;">
            <a href="index.php" class="btn btn-outline" style="margin-right: 15px;">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
            <div style="margin-left: auto;">
                <button class="btn btn-primary" onclick="openModal('addTransaksiModal')">
                    <i class="fas fa-plus"></i> Transaksi Baru
                </button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>Tanggal</th>
                    <th>Keterangan</th>
                    <th class="text-end">Debet</th>
                    <th class="text-end">Kredit</th>
                    <th class="text-end">Saldo</th>
                    <th>Admin</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($transaksiList)): ?>
                    <tr><td colspan="8" class="text-center text-muted" style="padding: 40px;">Belum ada riwayat transaksi</td></tr>
                <?php else: ?>
                    <?php 
                    $currentRunningBalance = $saldo;
                    foreach ($transaksiList as $t): 
                    ?>
                        <tr>
                            <td><?= formatTanggal($t['tanggal']) ?></td>
                            <td><?= htmlspecialchars($t['keterangan'] ?: '-') ?></td>
                            <td class="text-danger text-end">
                                <?= $t['tipe'] === 'penarikan' ? formatRupiah($t['jumlah']) : '-' ?>
                            </td>
                            <td class="text-success text-end">
                                <?= $t['tipe'] === 'setoran' ? formatRupiah($t['jumlah']) : '-' ?>
                            </td>
                            <td class="fw-bold text-end">
                                <?= formatRupiah($currentRunningBalance) ?>
                            </td>
                            <td><small class="text-muted"><i class="fas fa-user-edit"></i> <?= htmlspecialchars($t['admin_name'] ?: 'System') ?></small></td>
                            <td>
                                <div class="action-buttons">
                                    <a href="transaksi.php?siswa_id=<?= $siswaId ?>&edit=<?= $t['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 transaksi ini?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $t['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 
                        if ($t['tipe'] === 'setoran') {
                            $currentRunningBalance -= $t['jumlah'];
                        } else {
                            $currentRunningBalance += $t['jumlah'];
                        }
                        endforeach; 
                        ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Transaksi Modal -->
<div class="modal" id="addTransaksiModal">
    <div class="modal-header">
        <h3>Catat Transaksi Baru</h3>
        <button class="modal-close" onclick="closeModal('addTransaksiModal')"><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-row">
                <div class="form-group">
                    <label>Tipe Transaksi <span class="required">*</span></label>
                    <select name="tipe" class="form-control" required>
                        <option value="setoran">Setoran (Masuk)</option>
                        <option value="penarikan">Penarikan (Keluar)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tanggal <span class="required">*</span></label>
                    <input type="date" name="tanggal" class="form-control" required value="<?= date('Y-m-d') ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Jumlah (Rp) <span class="required">*</span></label>
                <input type="text" name="jumlah" class="form-control" required placeholder="0" oninput="formatCurrencyInput(this)">
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <textarea name="keterangan" class="form-control" rows="2" placeholder="Catatan tambahan (opsional)"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addTransaksiModal')">Batal</button>
            <button type="submit" class="btn btn-primary">Simpan Transaksi</button>
        </div>
    </form>
</div>

<!-- Edit Transaksi Modal -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editTransaksiModal'));</script>
<div class="modal" id="editTransaksiModal">
    <div class="modal-header">
        <h3>Edit Transaksi Tabungan</h3>
        <button class="modal-close" onclick="window.location='transaksi.php?siswa_id=<?= $siswaId ?>'"><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-row">
                <div class="form-group">
                    <label>Tipe Transaksi <span class="required">*</span></label>
                    <select name="tipe" class="form-control" required>
                        <option value="setoran" <?= $editData['tipe'] === 'setoran' ? 'selected' : '' ?>>Setoran (Masuk)</option>
                        <option value="penarikan" <?= $editData['tipe'] === 'penarikan' ? 'selected' : '' ?>>Penarikan (Keluar)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tanggal <span class="required">*</span></label>
                    <input type="date" name="tanggal" class="form-control" required value="<?= $editData['tanggal'] ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Jumlah (Rp) <span class="required">*</span></label>
                <input type="text" name="jumlah" class="form-control" required 
                       value="<?= number_format($editData['jumlah'], 0, '', '.') ?>"
                       oninput="formatCurrencyInput(this)">
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <textarea name="keterangan" class="form-control" rows="2"><?= htmlspecialchars($editData['keterangan']) ?></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.location='transaksi.php?siswa_id=<?= $siswaId ?>'">Batal</button>
            <button type="submit" class="btn btn-primary">Perbarui</button>
        </div>
    </form>
</div>
<?php endif; ?>

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