<?php

namespace App\Http\Controllers\API\Tenant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant\Sale;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
    /**
     * Get Transaction History (Sales)
     */
    public function transactions(Request $request)
    {
        $startDate = $request->query('start_date', now()->subDays(30)->toDateString());
        $endDate = $request->query('end_date', now()->toDateString());

        $sales = Sale::with(['items.variant.product', 'customer'])
            ->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59'])
            ->orderBy('created_at', 'desc')
            ->get();

        $summary = [
            'total_sales_count' => $sales->count(),
            'total_revenue' => $sales->sum('total'),
            'average_ticket' => $sales->count() > 0 ? $sales->avg('total') : 0,
        ];

        return response()->json([
            'meta' => [
                'start_date' => $startDate,
                'end_date' => $endDate,
            ],
            'summary' => $summary,
            'transactions' => $sales,
        ]);
    }
}
