<?php
class RevenueReportController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('reports/daily-revenue', [
            'title' => lang('finance.daily_revenue'),
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.daily_revenue')],
            ],
        ]);
    }

    public function data(Request $request): void
    {
        $date = $request->get('date', date('Y-m-d'));
        $db   = $this->db();

        $summary = $db->fetchAll(
            "SELECT pm.name_en AS method, pm.method_type, COUNT(p.id) AS count, COALESCE(SUM(p.amount),0) AS total
             FROM payments p
             JOIN payment_methods pm ON p.payment_method_id=pm.id
             WHERE p.payment_date=? AND p.status='completed' AND p.is_deleted=0
             GROUP BY pm.id, pm.name_en, pm.method_type
             ORDER BY total DESC",
            [$date]
        );

        $grandTotal = (float)$db->fetchColumn(
            "SELECT COALESCE(SUM(amount),0) FROM payments WHERE payment_date=? AND status='completed' AND is_deleted=0",
            [$date]
        );

        $transactionCount = (int)$db->fetchColumn(
            "SELECT COUNT(*) FROM payments WHERE payment_date=? AND status='completed' AND is_deleted=0",
            [$date]
        );

        // Last 7 days for chart
        $chartData = $db->fetchAll(
            "SELECT payment_date, COALESCE(SUM(amount),0) AS total
             FROM payments
             WHERE payment_date BETWEEN DATE_SUB(?, INTERVAL 6 DAY) AND ? AND status='completed' AND is_deleted=0
             GROUP BY payment_date
             ORDER BY payment_date",
            [$date, $date]
        );

        $this->json([
            'success'    => true,
            'summary'    => $summary,
            'grandTotal' => $grandTotal,
            'transactionCount' => $transactionCount,
            'chartData'  => $chartData,
        ]);
    }
}