<?php

namespace App\Http\Controllers;

use App\Models\Promo;
use Illuminate\Http\Request;
use Carbon\Carbon;

class PromoController extends Controller
{
    public function index()
    {
        return response()->json(Promo::latest()->get());
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'code' => 'required|string|unique:promos,code',
            'discount_amount' => 'required|numeric',
            'type' => 'required|in:percent,flat',
            'expired_at' => 'nullable|date',
            'is_active' => 'boolean'
        ]);

        $promo = Promo::create($validated);
        return response()->json(['success' => true, 'promo' => $promo]);
    }

    public function update(Request $request, $id)
    {
        $promo = Promo::findOrFail($id);
        $validated = $request->validate([
            'code' => 'required|string|unique:promos,code,' . $id,
            'discount_amount' => 'required|numeric',
            'type' => 'required|in:percent,flat',
            'expired_at' => 'nullable|date',
            'is_active' => 'boolean'
        ]);

        $promo->update($validated);
        return response()->json(['success' => true, 'promo' => $promo]);
    }

    public function destroy($id)
    {
        $promo = Promo::findOrFail($id);
        $promo->delete();
        return response()->json(['success' => true]);
    }

    /**
     * Frontend: Check Promo Code
     */
    public function check(Request $request)
    {
        $request->validate(['code' => 'required|string']);
        
        $promo = Promo::where('code', $request->code)
            ->where('is_active', true)
            ->where(function($q) {
                $q->whereNull('expired_at')->orWhere('expired_at', '>', Carbon::now());
            })
            ->first();

        if (!$promo) {
            return response()->json(['success' => false, 'message' => 'Kode promo tidak valid atau sudah kadaluarsa'], 404);
        }

        return response()->json([
            'success' => true,
            'code' => $promo->code,
            'discount_amount' => $promo->discount_amount,
            'type' => $promo->type
        ]);
    }
}
