<?php

namespace App\Http\Controllers\Api;

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

class VoucherApiController extends Controller
{
    /**
     * Validate voucher code
     */
    public function validate(Request $request)
    {
        $code = strtoupper($request->input('code'));
        $totalAmount = (int) $request->input('total_amount', 0);
        $customerEmail = $request->input('customer_email');
        
        if (!$code) {
            return response()->json([
                'valid' => false,
                'message' => 'Voucher code is required'
            ], 400);
        }
        
        if ($totalAmount <= 0) {
            return response()->json([
                'valid' => false,
                'message' => 'Total amount is required'
            ], 400);
        }
        
        // Find voucher
        $voucher = Voucher::where('code', $code)->first();
        
        if (!$voucher) {
            return response()->json([
                'valid' => false,
                'message' => 'Voucher tidak ditemukan'
            ]);
        }
        
        // Validate voucher
        $validation = $voucher->validate($totalAmount, $customerEmail);
        
        if (!$validation['valid']) {
            return response()->json([
                'valid' => false,
                'message' => $validation['message']
            ]);
        }
        
        // Calculate discount
        $discountAmount = $voucher->calculateDiscount($totalAmount);
        $finalAmount = $totalAmount - $discountAmount;
        
        return response()->json([
            'valid' => true,
            'message' => 'Voucher berhasil diterapkan!',
            'voucher' => [
                'id' => $voucher->id,
                'code' => $voucher->code,
                'type' => $voucher->type,
                'value' => $voucher->value,
                'description' => $voucher->description,
            ],
            'discount' => [
                'amount' => $discountAmount,
                'formatted' => 'Rp ' . number_format($discountAmount, 0, ',', '.'),
            ],
            'total' => [
                'original' => $totalAmount,
                'original_formatted' => 'Rp ' . number_format($totalAmount, 0, ',', '.'),
                'final' => $finalAmount,
                'final_formatted' => 'Rp ' . number_format($finalAmount, 0, ',', '.'),
            ],
        ]);
    }
}