<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Purchase;
use Illuminate\Http\Request;

class ReportController extends Controller
{
    /**
     * ✅ گزارش خریدها
     */
    public function purchases(Request $request)
    {
        $query = Purchase::query();

        // فیلتر توسط user
        if ($request->has('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        // فیلتر توسط status
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        // فیلتر توسط تاریخ
        if ($request->has('from_date')) {
            $query->whereDate('created_at', '>=', $request->from_date);
        }

        if ($request->has('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

        $purchases = $query->with('user')->paginate(50);

        return response()->json([
            'message' => 'Purchases report',
            'total' => $purchases->total(),
            'data' => $purchases,
        ]);
    }

    /**
     * ✅ آمار کلی
     */
    public function stats()
    {
        $totalPurchases = Purchase::count();
        $totalSeconds = Purchase::sum('seconds_added');
        $successPurchases = Purchase::where('status', 'success')->count();
        $pendingPurchases = Purchase::where('status', 'pending')->count();

        return response()->json([
            'total_purchases' => $totalPurchases,
            'total_seconds_added' => $totalSeconds,
            'total_hours' => round($totalSeconds / 3600, 2),
            'success_purchases' => $successPurchases,
            'pending_purchases' => $pendingPurchases,
        ]);
    }
}