<?php
session_start();
require '../config/database.php';

// 1. Validasi Akses: Sesuai logika sistem baru
if (!isset($_SESSION['user_logged_in']) || $_SESSION['role'] !== 'siswa' || !isset($_SESSION['id_siswa'])) {
    header("Location: ../login.php");
    exit();
}

$id_siswa = $_SESSION['id_siswa'];

try {
    // 2. Ambil data profil & saldo (Integrasi desain lama ke database baru)
    $stmt = $pdo->prepare("SELECT s.*, k.nama_kelas FROM siswa s JOIN kelas k ON s.id_kelas = k.id_kelas WHERE s.id_siswa = ?");
    $stmt->execute([$id_siswa]);
    $siswa = $stmt->fetch();

    if (!$siswa) {
        session_destroy();
        header("Location: ../login.php?error=data_not_found");
        exit();
    }

    // 3. Ringkasan Saldo (Valid & Pending)
    $stmt_count = $pdo->prepare("SELECT 
        SUM(CASE WHEN jenis_transaksi = 'setoran' AND status = 'valid' THEN jumlah ELSE 0 END) as setoran_valid,
        SUM(CASE WHEN jenis_transaksi = 'setoran' AND status = 'pending' THEN jumlah ELSE 0 END) as setoran_pending
        FROM transaksi WHERE id_siswa = ?");
    $stmt_count->execute([$id_siswa]);
    $ringkasan = $stmt_count->fetch();

} catch (PDOException $e) {
    die("Kesalahan Database: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Madu Mandiri Saving</title>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        /* Mengadopsi CSS Variable dari desain lama */
        :root {
            --primary-blue: #4a4ff2;
            --secondary-blue: #5b64ff;
            --bg-color: #f0f4f9;
            --text-color: #343a40;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        body { font-family: 'Nunito', sans-serif; background-color: var(--bg-color); color: var(--text-color); }
        .header { background-color: #fff; box-shadow: var(--card-shadow); padding: 1rem; border-radius: 50px !important; margin-bottom: 1.5rem; }
        .saldo-card { 
            background: linear-gradient(135deg, var(--primary-blue), var(--secondary-blue)); 
            color: #fff; border-radius: 1.5rem; padding: 2rem; box-shadow: var(--card-shadow); 
        }
        .saldo-amount { font-size: 2.5rem; font-weight: 700; }
        .menu-card { 
            border-radius: 1rem; box-shadow: var(--card-shadow); transition: transform 0.2s; 
            text-decoration: none; color: var(--text-color); border: none;
        }
        .menu-card:hover { transform: translateY(-5px); }
        .menu-icon { font-size: 2.5rem; margin-bottom: 0.5rem; }
    </style>
</head>
<body>
<div class="container py-4">
    <header class="d-flex justify-content-between align-items-center header">
        <div class="d-flex align-items-center" role="button" data-bs-toggle="modal" data-bs-target="#modalKeamanan">
            <i class="bi bi-person-circle fs-3 me-2 text-primary"></i>
            <h5 class="mb-0"><i>Halo,</i> <b><?= htmlspecialchars($siswa['nama_siswa']) ?></b></h5>
        </div>
        <a href="../logout.php" class="btn btn-outline-danger btn-sm rounded-pill px-3 fw-bold">Logout</a>
    </header>

    <div class="saldo-card mb-4">
        <p class="mb-1 opacity-75">Saldo Tabungan Anda <b>Rp.</b></p>
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="saldo-amount" id="saldo-text">******</h2>
            <button class="btn text-white p-0" onclick="toggleSaldo()">
                <i class="bi bi-eye-slash-fill fs-3" id="eye-icon"></i>
            </button>
        </div>
        <div class="mt-3 pt-3 border-top border-white border-opacity-25 small">
            <div class="d-flex justify-content-between">
                <span>Setoran Valid:</span> <strong>Rp <?= number_format($ringkasan['setoran_valid'] ?? 0, 0, ',', '.') ?></strong>
            </div>
            <div class="d-flex justify-content-between opacity-75">
                <span>Setoran Pending:</span> <strong>Rp <?= number_format($ringkasan['setoran_pending'] ?? 0, 0, ',', '.') ?></strong>
            </div>
        </div>
    </div>

    <div class="row row-cols-2 row-cols-md-4 g-3 text-center mb-4">
        <div class="col">
            <div class="card menu-card h-100 py-3" data-bs-toggle="modal" data-bs-target="#modalSetoran" role="button">
                <i class="bi bi-cash-stack menu-icon text-success"></i>
                <span class="fw-bold small">SETORAN</span>
            </div>
        </div>
        <div class="col">
            <div class="card menu-card h-100 py-3" data-bs-toggle="modal" data-bs-target="#modalPenarikan" role="button">
                <i class="bi bi-wallet2 menu-icon text-danger"></i>
                <span class="fw-bold small">PENARIKAN</span>
            </div>
        </div>
        <div class="col">
            <div class="card menu-card h-100 py-3" data-bs-toggle="modal" data-bs-target="#modalTransfer" role="button">
                <i class="bi bi-arrow-left-right menu-icon text-primary"></i>
                <span class="fw-bold small">TRANSFER</span>
            </div>
        </div>
        <div class="col">
            <div class="card menu-card h-100 py-3" data-bs-toggle="modal" data-bs-target="#modalPayment" role="button">
                <i class="bi bi-credit-card-2-front menu-icon text-warning"></i>
                <span class="fw-bold small">PAYMENT</span>
            </div>
        </div>
    </div>

    <div class="card menu-card p-3 mb-4 d-flex flex-row justify-content-between align-items-center">
        <div role="button" data-bs-toggle="collapse" data-bs-target="#collapseRekap" class="flex-grow-1">
            <i class="bi bi-journal-text me-2 fs-4 text-info"></i>
            <span class="fw-bold">Rekap Transaksi</span>
        </div>
        <a href="cetak_pdf.php" target="_blank" class="btn btn-light btn-sm"><i class="bi bi-file-pdf text-danger"></i> PDF</a>
    </div>

    <div class="collapse" id="collapseRekap">
        <div class="card card-body border-0 shadow-sm rounded-4" id="rekap-content">
            <p class="text-center text-muted">Memuat data...</p>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Logika Toggle Saldo
    let saldoVisible = false;
    const realSaldo = "<?= number_format($siswa['saldo'] ?? 0, 0, ',', '.') ?>";
    function toggleSaldo() {
        saldoVisible = !saldoVisible;
        $('#saldo-text').text(saldoVisible ? realSaldo : "******");
        $('#eye-icon').toggleClass('bi-eye-slash-fill bi-eye-fill');
    }

    // AJAX Handling Transaksi (Setoran, dll)
    $(document).on('submit', '.ajax-form', function(e) {
        e.preventDefault();
        const btn = $(this).find('button[type="submit"]');
        btn.prop('disabled', true).text('Memproses...');
        
        $.ajax({
            url: 'proses_transaksi.php',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(res) {
                alert(res.message);
                if(res.success) location.reload();
                else btn.prop('disabled', false).text('Kirim');
            }
        });
    });

    // Memuat Rekap saat Collapse dibuka
    $('#collapseRekap').on('show.bs.collapse', function () {
        $('#rekap-content').load('fetch_rekap_transaksi.php');
    });
</script>
</body>
</html>