<?php
header('Content-Type: application/json');
$response = ['success' => false, 'chartData' => null, 'statusSummary' => null, 'message' => 'Gagal memuat data laporan deposit.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) {
    http_response_code(401);
    $response['message'] = 'Sesi berakhir. Silakan login kembali.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in get_deposit_report.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

try {
    $userId = $_SESSION['user_id'];
    $dateStartStr = $_GET['date_start'] ?? date('Y-m-d', strtotime('-6 days'));
    $dateEndStr = $_GET['date_end'] ?? date('Y-m-d');

    $dateStart = (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateStartStr)) ? $dateStartStr : null;
    $dateEnd = (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateEndStr)) ? $dateEndStr : null;

    if (!$dateStart || !$dateEnd) {
        throw new InvalidArgumentException("Format tanggal tidak valid.");
    }
    if (strtotime($dateEnd) < strtotime($dateStart)) {
         throw new InvalidArgumentException("Tanggal akhir tidak boleh sebelum tanggal mulai.");
    }

    $dateEndForQuery = $dateEnd . ' 23:59:59';

    $sqlChart = "SELECT DATE(created_at) as deposit_date, SUM(amount) as total_amount, COUNT(id) as deposit_count
                 FROM deposits
                 WHERE user_id = :user_id AND status = 'success' AND created_at >= :date_start AND created_at <= :date_end
                 GROUP BY DATE(created_at)
                 ORDER BY deposit_date ASC";
    $stmtChart = $pdo->prepare($sqlChart);
    $stmtChart->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtChart->bindParam(':date_start', $dateStart);
    $stmtChart->bindParam(':date_end', $dateEndForQuery);
    $stmtChart->execute();
    $dailyDeposits = $stmtChart->fetchAll(PDO::FETCH_ASSOC);

    $chartLabels = [];
    $chartDataAmounts = [];
    $chartDataCounts = [];

    $currentDate = new DateTime($dateStart);
    $endDateObj = new DateTime($dateEnd);
    $interval = new DateInterval('P1D');
    $dateRange = new DatePeriod($currentDate, $interval, $endDateObj->modify('+1 day'));

    $depositsByDate = [];
    foreach ($dailyDeposits as $row) {
        $depositsByDate[$row['deposit_date']] = ['total_amount' => $row['total_amount'], 'deposit_count' => $row['deposit_count']];
    }

    foreach ($dateRange as $date) {
        $formattedDate = $date->format('Y-m-d');
        $chartLabels[] = $formattedDate;
        $chartDataAmounts[] = $depositsByDate[$formattedDate]['total_amount'] ?? 0;
        $chartDataCounts[] = $depositsByDate[$formattedDate]['deposit_count'] ?? 0;
    }

    $chartData = [
        'labels' => $chartLabels,
        'datasets' => [
            [
                'label' => 'Jumlah Deposit (Rp)',
                'data' => $chartDataAmounts,
                'borderColor' => 'rgb(75, 192, 192)',
                'backgroundColor' => 'rgba(75, 192, 192, 0.1)',
                'yAxisID' => 'yAmount',
                'tension' => 0.2,
                'fill' => true,
            ],
            [
                'label' => 'Total Transaksi Deposit',
                'data' => $chartDataCounts,
                'borderColor' => 'rgb(255, 99, 132)',
                'backgroundColor' => 'rgba(255, 99, 132, 0.1)',
                'yAxisID' => 'yCount',
                'tension' => 0.2,
                'fill' => false,
                'hidden' => true,
            ]
        ]
    ];

    $sqlSummary = "SELECT status, COUNT(id) as count, SUM(amount) as total_amount
                   FROM deposits
                   WHERE user_id = :user_id AND created_at >= :date_start AND created_at <= :date_end
                   GROUP BY status";
    $stmtSummary = $pdo->prepare($sqlSummary);
    $stmtSummary->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtSummary->bindParam(':date_start', $dateStart);
    $stmtSummary->bindParam(':date_end', $dateEndForQuery);
    $stmtSummary->execute();
    $statusSummaryRaw = $stmtSummary->fetchAll(PDO::FETCH_ASSOC);

    $statusSummary = [];
    $allStatuses = ['pending', 'success', 'failed', 'expired', 'canceled'];
    $summaryMap = [];
    foreach ($statusSummaryRaw as $row) {
        $summaryMap[strtolower($row['status'])] = $row;
    }

    foreach ($allStatuses as $status) {
         $count = $summaryMap[$status]['count'] ?? 0;
         $total_amount_val = $summaryMap[$status]['total_amount'] ?? 0;
         $statusSummary[] = [
             'status' => ucfirst($status),
             'status_key' => $status,
             'count' => (int)$count,
             'total_amount' => (float)$total_amount_val,
             'total_amount_formatted' => 'Rp ' . number_format($total_amount_val, 0, ',', '.')
         ];
    }

    $response['success'] = true;
    $response['chartData'] = $chartData;
    $response['statusSummary'] = $statusSummary;
    unset($response['message']);

} catch (InvalidArgumentException $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
} catch (\PDOException $e) {
    error_log("AJAX Get Deposit Report DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat memuat laporan deposit.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("AJAX Get Deposit Report General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
