<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\ActivationCode;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ActivationCodeController extends Controller
{
    public function index()
    {
        $codes = ActivationCode::latest()->get();

        return view('dashboard.codes.index', compact('codes'));
    }

    
public function store(Request $request)
{
    $request->validate([
        'owner_name'     => 'required|string|max:255',
        'duration_type'  => 'required|in:hour,day',
        'duration_value' => 'required|integer|min:1',
    ]);

    $expiresAt = now();

    if ($request->duration_type === 'hour') {
        $expiresAt = now()->addHours((int) $request->duration_value);
    } else {
        $expiresAt = now()->addDays((int) $request->duration_value);
    }

    ActivationCode::create([
        'code'           => strtoupper(Str::random(10)),
        'owner_name'     => $request->owner_name,
        'duration_type'  => $request->duration_type,
        'duration_value' => (int) $request->duration_value,
        'expires_at'     => $expiresAt,
    ]);

    return redirect()->back();
}

    public function disable($id)
    {
        ActivationCode::where('id', $id)
            ->update(['status' => 'disabled']);

        return redirect()->back();
    }
}

