<?php

namespace App\Http\Controllers;

use App\Models\Voucher;
use App\Models\VoucherAgent;
use App\Models\IspPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class VoucherController extends Controller
{
    public function index()
    {
        $vouchers = Voucher::orderBy('created_at', 'desc')->paginate(15);
        $agents = VoucherAgent::orderBy('name', 'asc')->get();
        $hotspotPlans = IspPlan::where('type', 'Hotspot')->orWhere('availability', 'Live')->get();

        $unusedCount = Voucher::where('status', 'Unused')->count();
        $redeemedCount = Voucher::where('status', 'Redeemed')->count();
        $totalBatchCount = Voucher::distinct('batch_code')->count('batch_code');

        return view('admin.finance.vouchers', compact(
            'vouchers',
            'agents',
            'hotspotPlans',
            'unusedCount',
            'redeemedCount',
            'totalBatchCount'
        ));
    }

    public function generateBatch(Request $request)
    {
        $request->validate([
            'package_name' => 'required|string',
            'price' => 'required|numeric|min:1',
            'quantity' => 'required|integer|min:1|max:100',
            'prefix' => 'nullable|string|max:6',
        ]);

        $batchCode = 'BATCH-' . Str::upper(Str::random(6));
        $prefix = Str::upper($request->prefix ?? 'WIFI');
        $qty = (int)$request->quantity;

        for ($i = 0; $i < $qty; $i++) {
            $code = $prefix . '-' . Str::upper(Str::random(8));
            Voucher::create([
                'batch_code' => $batchCode,
                'voucher_code' => $code,
                'package_name' => $request->package_name,
                'price' => $request->price,
                'status' => 'Unused',
            ]);
        }

        return redirect()->route('admin.finance.vouchers')->with('success', "Batch {$batchCode} generated with {$qty} vouchers!");
    }

    public function storeAgent(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string',
            'email' => 'nullable|email',
            'opening_float' => 'nullable|numeric|min:0',
        ]);

        $validated['current_float'] = $validated['opening_float'] ?? 0.00;
        $validated['commission_rate'] = 10.00;
        $validated['status'] = 'Active';

        VoucherAgent::create($validated);

        return redirect()->route('admin.finance.vouchers')->with('success', "Voucher Agent {$validated['name']} registered!");
    }
}
