<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivationCode;
use Illuminate\Http\Request;
use Carbon\Carbon;

class ActivationApiController extends Controller
{
    /**
     * Check activation code validity
     * Used by Flutter App
     */
    public function check(Request $request)
    {
        // Validate request
        $request->validate([
            'code' => 'required|string'
        ]);

        // Find activation code
        $activationCode = ActivationCode::where('code', $request->code)->first();

        /**
         * Case 1: Code not found
         */
        if (!$activationCode) {
            return response()->json([
                'status' => 'invalid',
                'message' => 'Activation code is invalid'
            ], 404);
        }

        /**
         * Case 2: Code disabled manually
         */
        if ($activationCode->status === 'disabled') {
            return response()->json([
                'status' => 'disabled',
                'message' => 'Activation code is disabled'
            ], 403);
        }

        /**
         * Case 3: Code expired
         */
        if (Carbon::now()->greaterThanOrEqualTo($activationCode->expires_at)) {
            return response()->json([
                'status' => 'expired',
                'message' => 'Activation code expired',
                'expired_at' => $activationCode->expires_at->toDateTimeString()
            ], 403);
        }

        /**
         * Case 4: Code is valid
         */
        return response()->json([
            'status' => 'valid',
            'message' => 'Activation code is valid',

            // Owner info
            'owner_name' => $activationCode->owner_name,

            // Dates
            'created_at' => $activationCode->created_at->toDateTimeString(),
            'expires_at' => $activationCode->expires_at->toDateTimeString(),

            // Remaining time (important for Flutter)
            'remaining_seconds' => Carbon::now()->diffInSeconds($activationCode->expires_at),
            'remaining_minutes' => Carbon::now()->diffInMinutes($activationCode->expires_at),
            'remaining_hours'   => Carbon::now()->diffInHours($activationCode->expires_at),
        ], 200);
    }
}

