<?php

namespace App\Http\Controllers\Api;

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

class ReconciliationController extends Controller
{
    public function stats(Request $request)
    {
        $this->authorize('view-reports');

        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());

        $base = Payment::join('sales', 'payments.sale_id', '=', 'sales.id')
            ->whereNotIn('sales.status', ['returned'])
            ->whereBetween(DB::raw('DATE(payments.created_at)'), [$startDate, $endDate]);

        $byMethod = (clone $base)
            ->groupBy('payments.payment_method')
            ->selectRaw('payments.payment_method as method, SUM(payments.amount) as total, COUNT(*) as count')
            ->orderByRaw('SUM(payments.amount) DESC')
            ->get();

        $totals = (clone $base)
            ->selectRaw('SUM(payments.amount) as grand_total, COUNT(*) as total_transactions, COUNT(DISTINCT payments.sale_id) as total_sales')
            ->first();

        return response()->json([
            'by_method'          => $byMethod,
            'grand_total'        => $totals->grand_total ?? 0,
            'total_transactions' => $totals->total_transactions ?? 0,
            'total_sales'        => $totals->total_sales ?? 0,
            'start_date'         => $startDate,
            'end_date'           => $endDate,
        ]);
    }

    public function index(Request $request)
    {
        $this->authorize('view-reports');

        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());
        $method    = $request->input('method');
        $perPage   = min((int) $request->input('per_page', 20), 100);

        $query = Payment::with(['sale' => function ($q) {
            $q->select('id', 'sale_number', 'customer_id', 'total', 'status')
              ->with('customer:id,name');
        }])
            ->join('sales', 'payments.sale_id', '=', 'sales.id')
            ->whereNotIn('sales.status', ['returned'])
            ->whereBetween(DB::raw('DATE(payments.created_at)'), [$startDate, $endDate])
            ->select('payments.*');

        if ($method) {
            $query->where('payments.payment_method', $method);
        }

        return response()->json($query->latest('payments.created_at')->paginate($perPage));
    }
}
