<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\LoyaltyPoint;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoyaltyController extends Controller
{
    /**
     * Get loyalty program settings.
     */
    public function settings()
    {
        $settings = Setting::where('key', 'like', 'loyalty_%')
            ->get()
            ->pluck('value', 'key');

        return response()->json(['data' => $settings]);
    }

    /**
     * Update loyalty program settings.
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'loyalty_enabled' => 'nullable|boolean',
            'loyalty_points_per_currency' => 'nullable|numeric|min:0',
            'loyalty_currency_per_point' => 'nullable|numeric|min:0',
            'loyalty_min_redeem_points' => 'nullable|integer|min:0',
        ]);

        foreach ($request->all() as $key => $value) {
            if (str_starts_with($key, 'loyalty_')) {
                Setting::updateOrCreate(
                    ['key' => $key],
                    ['value' => (string) $value, 'is_public' => false]
                );
            }
        }

        return response()->json([
            'message' => 'تم تحديث إعدادات برنامج الولاء بنجاح',
        ]);
    }

    /**
     * List customers with loyalty balances.
     */
    public function customers(Request $request)
    {
        $customers = Customer::select('customers.*')
            ->selectSub(function ($query) {
                $query->from('loyalty_points')
                    ->whereColumn('loyalty_points.customer_id', 'customers.id')
                    ->where('type', 'earned')
                    ->selectRaw('COALESCE(SUM(points), 0)');
            }, 'total_earned')
            ->selectSub(function ($query) {
                $query->from('loyalty_points')
                    ->whereColumn('loyalty_points.customer_id', 'customers.id')
                    ->where('type', 'redeemed')
                    ->selectRaw('COALESCE(SUM(points), 0)');
            }, 'total_redeemed')
            ->orderBy('total_earned', 'desc');

        if ($request->filled('search')) {
            $search = $request->search;
            $customers->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        return response()->json($customers->paginate($request->get('per_page', 20)));
    }
}
