<?php
/**
 * riwayat_user.php
 * Mengembalikan SEMUA riwayat deposit milik user berdasarkan email.
 * Frontend melakukan filter client-side (pending / approved / rejected).
 *
 * GET ?email=xxx@xxx.com
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once '../config/db.php';

// Buat tabel jika belum ada
$conn->query("
    CREATE TABLE IF NOT EXISTS deposit (
        id          INT AUTO_INCREMENT PRIMARY KEY,
        nama        VARCHAR(100)   NOT NULL,
        email       VARCHAR(100)   NOT NULL,
        telepon     VARCHAR(20)    NOT NULL,
        jumlah      BIGINT         NOT NULL,
        bukti       VARCHAR(255)   NOT NULL,
        status      ENUM('pending','approved','rejected') DEFAULT 'pending',
        created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");

// Validasi email
$email = trim($_GET['email'] ?? '');
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'status'  => false,
        'message' => 'Email tidak valid.',
        'data'    => [],
        'stat'    => []
    ]);
    exit;
}

// Ambil SEMUA data tanpa limit - frontend filter client-side
$dst = $conn->prepare("
    SELECT id, nama, jumlah, status, bukti, created_at
    FROM deposit
    WHERE email = ?
    ORDER BY created_at DESC
");
$dst->bind_param('s', $email);
$dst->execute();
$rows = $dst->get_result()->fetch_all(MYSQLI_ASSOC);
$dst->close();

// Statistik
// Bagian Statistik di riwayat.php
$stt = $conn->prepare("
    SELECT
        COUNT(*) AS total,
        IFNULL(SUM(status = 'approved'), 0) AS approved,
        IFNULL(SUM(status = 'pending'), 0) AS pending,
        IFNULL(SUM(status = 'rejected'), 0) AS rejected,
        IFNULL(SUM(CASE WHEN status = 'approved' THEN jumlah ELSE 0 END), 0) AS total_masuk
    FROM deposit
    WHERE email = ?
");
$stt->bind_param('s', $email);
$stt->execute();
$stat = $stt->get_result()->fetch_assoc();
$stt->close();

// Format tiap baris
foreach ($rows as &$r) {
    $r['jumlah_fmt']  = 'Rp ' . number_format($r['jumlah'], 0, ',', '.');
    $r['created_fmt'] = date('d M Y, H:i', strtotime($r['created_at']));
}
unset($r);

echo json_encode([
    'status'  => true,
    'message' => 'OK',
    'email'   => $email,
    'stat'    => [
        'total'           => (int)$stat['total'],
        'approved'        => (int)$stat['approved'],
        'pending'         => (int)$stat['pending'],
        'rejected'        => (int)$stat['rejected'],
        'total_masuk'     => (int)$stat['total_masuk'],
        'total_masuk_fmt' => 'Rp ' . number_format($stat['total_masuk'], 0, ',', '.'),
    ],
    'data' => $rows,
], JSON_UNESCAPED_UNICODE);