<?php

namespace App\Http\Controllers\Admin;

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

class DepositRuleController extends Controller
{
    public function index(Request $request)
    {
        $q = DepositRule::query();

        if ($s = $request->get('s')) {
            $q->where(function($qq) use ($s){
                $qq->where('calc_type', 'like', "%$s%")
                   ->orWhere('value', 'like', "%$s%");
            });
        }

        // প্রথমে min_amount ASC, তারপর max_amount (null = infinity) শেষে
        $rules = $q->orderBy('min_amount')
                   ->orderByRaw('max_amount IS NULL, max_amount ASC')
                   ->paginate(12)->withQueryString();

        return view('admin.deposit_rules.index', compact('rules'));
    }

    public function create()
    {
        $rule = new DepositRule(['is_active'=>true, 'calc_type'=>'flat']);
        return view('admin.deposit_rules.create', compact('rule'));
    }

    public function store(Request $request)
    {
        $data = $this->validateData($request);

        // ওভারল্যাপ চেক
        if ($conflict = $this->findOverlap(null, $data['min_amount'], $data['max_amount'])) {
            return back()->withErrors([
                'min_amount' => 'এই রেঞ্জটি বিদ্যমান রুলের সাথে ওভারল্যাপ করছে: '
                    . number_format($conflict->min_amount) . ' - ' . ($conflict->max_amount ? number_format($conflict->max_amount) : '∞'),
            ])->withInput();
        }

        DepositRule::create($data);

        return redirect()->route('admin.deposit_rules.index')->with('success', 'Rule created.');
    }

    public function edit(DepositRule $deposit_rule)
    {
        return view('admin.deposit_rules.edit', ['rule' => $deposit_rule]);
    }

    public function update(Request $request, DepositRule $deposit_rule)
    {
        $data = $this->validateData($request);

        // ওভারল্যাপ চেক (নিজেকে বাদ দিয়ে)
        if ($conflict = $this->findOverlap($deposit_rule->id, $data['min_amount'], $data['max_amount'])) {
            return back()->withErrors([
                'min_amount' => 'এই রেঞ্জটি বিদ্যমান রুলের সাথে ওভারল্যাপ করছে: '
                    . number_format($conflict->min_amount) . ' - ' . ($conflict->max_amount ? number_format($conflict->max_amount) : '∞'),
            ])->withInput();
        }

        $deposit_rule->update($data);

        return redirect()->route('admin.deposit_rules.index')->with('success', 'Rule updated.');
    }

    public function destroy(DepositRule $deposit_rule)
    {
        $deposit_rule->delete();
        return back()->with('success', 'Rule removed.');
    }

    public function toggle(DepositRule $deposit_rule)
    {
        $deposit_rule->update(['is_active' => !$deposit_rule->is_active]);
        return back()->with('success', 'Status updated.');
    }

    // ---------- helpers ----------
    protected function validateData(Request $request): array
    {
        $data = $request->validate([
            'min_amount' => ['required','integer','min:0'],
            'max_amount' => ['nullable','integer','gt:min_amount'],
            'calc_type'  => ['required','in:flat,percent'],
            'value'      => ['required','numeric','min:0.01'],
            'is_active'  => ['sometimes','boolean'],
        ], [
            'max_amount.gt' => 'Max amount অবশ্যই Min থেকে বড় হতে হবে।',
        ]);

        // percent হলে 0.01–100 সীমা
        if ($data['calc_type'] === 'percent' && ($data['value'] <= 0 || $data['value'] > 100)) {
            return back()->withErrors(['value' => 'Percent হলে value 0.01% থেকে 100%–এর মধ্যে হতে হবে.'])->withInput()->throwResponse();
        }

        // checkbox না থাকলে false
        $data['is_active'] = (bool) ($data['is_active'] ?? false);

        return $data;
    }

    /**
     * ওভারল্যাপ ডিটেক্টর
     * overlap শর্ত: [minA, maxA] ⟂ [minB, maxB] (null = ∞)
     */
    protected function findOverlap(?int $ignoreId, int $min, ?int $max): ?DepositRule
    {
        $q = DepositRule::query();
        if ($ignoreId) $q->where('id','!=',$ignoreId);

        // A overlaps B if A.min <= B.max && (A.max is null or A.max >= B.min)
        $q->where(function($w) use ($min, $max){
            $w->where('min_amount', '<=', ($max ?? PHP_INT_MAX))
              ->where(function($ww) use ($min){
                  $ww->whereNull('max_amount')->orWhere('max_amount', '>=', $min);
              });
        });

        return $q->orderBy('min_amount')->first();
    }
}
