<?php

namespace App\Http\Controllers\Api;

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

class GiftCardController extends Controller
{
    /**
     * Redeem a gift card code.
     */
    public function redeem(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:50',
        ]);

        $giftCard = GiftCard::where('code', $request->code)
            ->where('is_active', true)
            ->first();

        if (!$giftCard) {
            return response()->json([
                'message' => 'كود بطاقة الهدية غير صالح',
            ], 422);
        }

        if ($giftCard->expires_at && $giftCard->expires_at < now()) {
            return response()->json([
                'message' => 'انتهت صلاحية بطاقة الهدية',
            ], 422);
        }

        if ($giftCard->balance <= 0) {
            return response()->json([
                'message' => 'رصيد بطاقة الهدية منتهي',
            ], 422);
        }

        if ($giftCard->redeemed_by && $giftCard->redeemed_by !== $request->user()->id) {
            return response()->json([
                'message' => 'هذه البطاقة مستخدمة من قبل شخص آخر',
            ], 422);
        }

        // Mark as redeemed by this customer if first use
        if (!$giftCard->redeemed_by) {
            $giftCard->update([
                'redeemed_by' => $request->user()->id,
                'redeemed_at' => now(),
            ]);
        }

        return response()->json([
            'message' => 'تم التحقق من بطاقة الهدية بنجاح',
            'data' => [
                'code' => $giftCard->code,
                'balance' => $giftCard->balance,
                'original_amount' => $giftCard->amount,
            ],
        ]);
    }
}
