<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PromoDetails;
use Illuminate\Support\Facades\Log;

class BonusController extends Controller
{
    /**
     * ===============================
     * GET PROMO DETAILS (AJAX / API)
     * ===============================
     */
   public function getPromoDetails(Request $request)
{
    $selectName = trim($request->input('select_name'));

    Log::info('PROMO DEBUG - REQUEST', [
        'select_name' => $selectName,
        'all_request' => $request->all(),
    ]);

    if (!$selectName || $selectName === '0') {
        return response()->json([
            'status'  => false,
            'message' => 'Promo tidak dipilih'
        ]);
    }

    // ===============================
    // JIKA ANGKA → CARI BY ID
    // JIKA STRING → CARI BY select_name
    // ===============================
    $promo = is_numeric($selectName)
        ? PromoDetails::where('id', (int) $selectName)->first()
        : PromoDetails::where('select_name', $selectName)->first();

    if (!$promo) {
        Log::error('PROMO DEBUG - PROMO TIDAK DITEMUKAN', [
            'select_name' => $selectName
        ]);

        return response()->json([
            'status'  => false,
            'message' => 'Promo tidak tersedia'
        ]);
    }

    return response()->json([
        'status' => true,
        'data' => [
            'judul'         => $promo->promo_name,
            'jenis_promosi' => $promo->jenis_promosi,
            'min_deposit'   => (int) $promo->min_deposit,
            'max_bonus'     => (int) $promo->max_bonus,
            'type'          => $promo->type,
            'turnover'      => $promo->turnover_multiplier,
        ]
    ]);
}


    /**
     * ===============================
     * ADD BONUS (ADMIN)
     * ===============================
     */
    public function addBonus(Request $request)
    {
        $request->validate([
            'judul'         => 'required|string',
            'jenis_promosi' => 'required|string',
            'min_deposit'   => 'required|numeric',
            'max_bonus'     => 'required|numeric',
            'type'          => 'required|string',
        ]);

        $promo = new PromoDetails();
        $promo->promo_name           = $request->judul;
        $promo->jenis_promosi        = $request->jenis_promosi;
        $promo->min_deposit          = $request->min_deposit;
        $promo->max_bonus            = $request->max_bonus;
        $promo->type                 = $request->type;
        $promo->turnover_multiplier  = $request->turnover_multiplier ?? 1;
        $promo->status               = '1';

        // IDENTITAS PROMO (INI YANG DIKIRIM KE AJAX)
        $promo->select_name = strtolower(
            preg_replace('/[^a-z0-9]+/', '_', $request->judul)
        );

        $promo->save();

        return response()->json([
            'status'  => true,
            'message' => 'Promo berhasil ditambahkan'
        ]);
    }
}
