<?php

namespace App\Http\Controllers;

use App\Models\LoyaltyTransaction;
use App\Models\Customer;
use Illuminate\Http\Request;

class LoyaltyController extends Controller
{
    /**
     * Display the loyalty dashboard.
     */
    public function index(Request $request)
    {
        $query = LoyaltyTransaction::query()->with(['customer', 'invoice']);

        // Filters
        if ($request->has('customer_id') && $request->customer_id != '') {
            $query->where('customer_id', $request->customer_id);
        }

        if ($request->has('type') && $request->type != '') {
            $query->where('type', $request->type);
        }

        if ($request->has('date_from') && $request->date_from != '') {
            $query->whereDate('date', '>=', $request->date_from);
        }

        if ($request->has('date_to') && $request->date_to != '') {
            $query->whereDate('date', '<=', $request->date_to);
        }

        $transactions = $query->latest()->paginate(20);

        // Summary Stats
        $totalEarned = LoyaltyTransaction::where('type', 'earned')->sum('points');
        $totalRedeemed = LoyaltyTransaction::where('type', 'redeemed')->sum('points');

        // This is an approximation as points belong to customers.
        // A more accurate way is Customer::sum('loyalty_points') if the column is maintained.
        // But we can check if that column was added.
        $totalLiability = Customer::sum('loyalty_points');

        $customers = Customer::orderBy('name')->get();

        return view('loyalty.index', compact('transactions', 'totalEarned', 'totalRedeemed', 'totalLiability', 'customers'));
    }
}
