<?php

namespace App\Http\Controllers;

use App\Models\Voucher;
use App\Models\VoucherUsage;
use Illuminate\Http\Request;

class VoucherCheckController extends Controller
{
    public function index()
    {
        return view('public.check');
    }

    public function check(Request $request)
    {
        $request->validate([
            'code'             => 'required|string',
            'purchase_amount'  => 'nullable|numeric|min:0',
        ]);

        $code = strtoupper(trim($request->code));
        $purchaseAmount = (float) ($request->purchase_amount ?? 0);
        $userIdentifier = $request->ip();

        $voucher = Voucher::where('code', $code)->first();

        if (!$voucher) {
            return response()->json([
                'valid'   => false,
                'message' => 'Kode voucher tidak ditemukan.',
            ], 404);
        }

        // Check if voucher has already been used
        if ($voucher->used_count > 0) {
            return response()->json([
                'valid'   => false,
                'message' => 'Voucher ini sudah pernah digunakan dan tidak dapat digunakan lagi.',
            ], 422);
        }

        // Check if user has already used this voucher
        if ($voucher->hasBeenUsedBy($userIdentifier)) {
            return response()->json([
                'valid'   => false,
                'message' => 'Anda sudah pernah menggunakan voucher ini sebelumnya.',
            ], 422);
        }

        if (!$voucher->isValid()) {
            $label = $voucher->status_label;
            return response()->json([
                'valid'   => false,
                'message' => "Voucher tidak dapat digunakan. Status: $label.",
            ], 422);
        }

        if ($purchaseAmount > 0 && $voucher->min_purchase > 0 && $purchaseAmount < $voucher->min_purchase) {
            return response()->json([
                'valid'   => false,
                'message' => 'Minimum pembelian untuk voucher ini adalah Rp ' . number_format($voucher->min_purchase, 0, ',', '.'),
            ], 422);
        }

        $discount = $purchaseAmount > 0 ? $voucher->calculateDiscount($purchaseAmount) : null;

        return response()->json([
            'valid'          => true,
            'message'        => 'Voucher valid dan dapat digunakan!',
            'voucher'        => [
                'code'           => $voucher->code,
                'name'           => $voucher->name,
                'description'    => $voucher->description,
                'type'           => $voucher->type,
                'discount_value' => $voucher->discount_value,
                'min_purchase'   => $voucher->min_purchase,
                'max_discount'   => $voucher->max_discount,
                'valid_until'    => $voucher->valid_until?->format('d M Y H:i'),
                'remaining_uses' => $voucher->remaining_uses,
            ],
            'discount_amount' => $discount,
            'final_price'     => $purchaseAmount > 0 ? max(0, $purchaseAmount - ($discount ?? 0)) : null,
        ]);
    }

    public function use(Request $request)
    {
        $request->validate([
            'code'             => 'required|string',
            'user_identifier'  => 'nullable|string',
            'order_id'         => 'nullable|string',
            'purchase_amount'  => 'nullable|numeric|min:0',
        ]);

        $code = strtoupper(trim($request->code));
        $purchaseAmount = (float) ($request->purchase_amount ?? 0);
        $userIdentifier = $request->user_identifier ?? $request->ip();
        $orderId = $request->order_id;

        $voucher = Voucher::where('code', $code)->first();

        if (!$voucher) {
            return response()->json([
                'success' => false,
                'message' => 'Kode voucher tidak ditemukan.',
            ], 404);
        }

        // Check if voucher has already been used
        if ($voucher->used_count > 0) {
            return response()->json([
                'success' => false,
                'message' => 'Voucher ini sudah pernah digunakan dan tidak dapat digunakan lagi.',
            ], 422);
        }

        // Check if user has already used this voucher
        if ($voucher->hasBeenUsedBy($userIdentifier)) {
            return response()->json([
                'success' => false,
                'message' => 'Anda sudah pernah menggunakan voucher ini sebelumnya.',
            ], 422);
        }

        if (!$voucher->isValid()) {
            $label = $voucher->status_label;
            return response()->json([
                'success' => false,
                'message' => "Voucher tidak dapat digunakan. Status: $label.",
            ], 422);
        }

        if ($purchaseAmount > 0 && $voucher->min_purchase > 0 && $purchaseAmount < $voucher->min_purchase) {
            return response()->json([
                'success' => false,
                'message' => 'Minimum pembelian untuk voucher ini adalah Rp ' . number_format($voucher->min_purchase, 0, ',', '.'),
            ], 422);
        }

        $discount = $purchaseAmount > 0 ? $voucher->calculateDiscount($purchaseAmount) : 0;

        // Record voucher usage
        VoucherUsage::create([
            'voucher_id'      => $voucher->id,
            'user_identifier' => $userIdentifier,
            'order_id'        => $orderId,
            'discount_applied' => $discount,
            'ip_address'      => $request->ip(),
        ]);

        // Increment used_count
        $voucher->increment('used_count');

        return response()->json([
            'success' => true,
            'message' => 'Voucher berhasil digunakan!',
            'voucher' => [
                'code'   => $voucher->code,
                'name'   => $voucher->name,
            ],
            'discount_applied' => $discount,
            'final_price'      => max(0, $purchaseAmount - $discount),
        ]);
    }
}
