<?php

namespace App\Http\Controllers;

use App\Models\Coupon;
use App\Models\CouponRedemption;
use App\Models\Ownership;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class CouponController extends Controller
{
    public function showRedeemPage()
    {
        $redemptions = Auth::user()->couponRedemptions()
                            ->with(['coupon.product'])
                            ->latest()
                            ->paginate(10);
        
        return view('redeem-coupon', compact('redemptions'));
    }

    public function redeem(Request $request)
    {
        $request->validate([
            'code' => 'required|string'
        ]);
    
        $code = strtoupper(trim($request->code));
        $user = Auth::user();
    
        // Find coupon
        $coupon = Coupon::where('code', $code)->first();
    
        if (!$coupon) {
            return back()
                ->withInput()
                ->with('error', '❌ Invalid coupon code. Please check and try again.');
        }
    
        // Check if coupon can be used
        if (!$coupon->canBeUsed()) {
            if ($coupon->isExpired()) {
                return back()
                    ->withInput()
                    ->with('error', '⏰ This coupon expired on ' . $coupon->expires_at->format('M j, Y'));
            }
            if ($coupon->isMaxUsesReached()) {
                return back()
                    ->withInput()
                    ->with('error', '🚫 This coupon has reached its maximum usage limit');
            }
            if (!$coupon->is_active) {
                return back()
                    ->withInput()
                    ->with('error', '⚠️ This coupon is no longer active');
            }
        }
    
        // Check if user already used this coupon
        if ($coupon->hasBeenUsedBy($user->id)) {
            return back()
                ->withInput()
                ->with('error', '🔁 You have already used this coupon code');
        }
    
        // Process redemption
        DB::beginTransaction();
        try {
            if ($coupon->type === 'balance') {
                // Add balance to user
                $user->increment('balance', $coupon->amount);
    
                // Record transaction
                Transaction::create([
                    'user_id' => $user->id,
                    'amount' => $coupon->amount,
                    'type' => 'coupon_redemption',
                    'status' => 1,
                    'notes' => 'Coupon: ' . $coupon->code
                ]);
    
                $message = '🎉 Coupon redeemed successfully! $' . number_format($coupon->amount, 2) . ' USDT has been added to your wallet.';
            } else {
                // Add product to inventory
                $product = $coupon->product;
                
                if (!$product) {
                    DB::rollBack();
                    return back()
                        ->withInput()
                        ->with('error', '❌ The product for this coupon is no longer available');
                }
    
                // Check if user already owns this product
                $ownership = Ownership::where('user_id', $user->id)
                                      ->where('product_id', $product->id)
                                      ->first();
    
                if ($ownership) {
                    // Increment quantity
                    $ownership->increment('quantity', $coupon->quantity);
                } else {
                    // Create new ownership
                    Ownership::create([
                        'user_id' => $user->id,
                        'product_id' => $product->id,
                        'slug' => Str::random(9),
                        'value' => $product->value,
                        'quantity' => $coupon->quantity,
                        'type' => 'coupon'
                    ]);
                }
    
                $message = '🎉 Coupon redeemed successfully! ' . $coupon->quantity . ' x ' . $product->name . ' has been added to your inventory.';
            }
    
            // Record redemption
            CouponRedemption::create([
                'coupon_id' => $coupon->id,
                'user_id' => $user->id,
                'redeemed_at' => now()
            ]);
    
            // Increment usage count
            $coupon->increment('used_count');
    
            DB::commit();
    
            return back()->with('message', $message);
    
        } catch (\Exception $e) {
            DB::rollBack();
            
            Log::error('Coupon redemption failed', [
                'exception' => $e,
                'user_id' => auth()->id(),
                'coupon_code' => request('code') ?? null,
            ]);
    
            return back()
                ->withInput()
                ->with('error', '❌ An error occurred while redeeming the coupon. Please try again or contact support.');
        }
    }
}