<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Clientsinfo;
use App\Models\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class ClientInformationController extends Controller
{
    public function getClientInformation(Request $request)
    {
        $appKey = env('CLIENT_INFORMATION_APP_NAME');
        $appSecret = env('CLIENT_INFORMATION_APP_SECRET');

        if ($appKey == null || $appSecret == null) {
            return response()->json(['message' => 'Client Information App is not configured'], 500);
        }

        if ($request->app_key != $appKey || $request->app_secret != $appSecret) {
            return response()->json(['message' => 'Invalid app credentials'], 403);
        }

        if ($request->contact == null) {
            return response()->json(['message' => 'Contact number is required'], 400);
        }

        $customer = Clientsinfo::where('contact_no', $request->contact)
            ->orWhere('other_contact', $request->contact)
            ->first();

        if (!$customer) {
            // dd('Customer not found');
            $url = env('TICKET_API_URL') . '/get-customer';
            // dd($url);
            $response = Http::post($url, [
                'contact' => $request->contact,
                'app_key' => $appKey,
                'app_secret' => $appSecret,
            ]);

            $data = $response->json(); // or $response->body()
            // dd($data)

            if (isset($data['message']) && $data['message'] == 'Client not found') {
                return response()->json(['message' => 'Customer not found'], 404);
            } else {
                return response()->json([
                    $data
                ], 200);
            }
        }

        $client = Client::with('pop', 'packages')->where('id', $customer->client_id)->first();

        // dd($client);

        if (!checkAPI()) {
            $lastSession = DB::table('radacct')
                ->where('username', $client->userid)
                ->latest('radacctid') // or use 'acctstarttime' if you want by time
                ->first();

            if ($lastSession && is_null($lastSession->acctstoptime)) {
                $status = 'online';
            } else {
                $status = 'offline';
            }
        }

        $token = Token::where('clientId', $client->id)
            ->where('status', 'active')
            ->get();


        if ($token->isNotEmpty()) {
            $tokenId = $token->pluck('token')->implode(', ');
        } else {
            $tokenId = null;
        }


        $data = [
            'customerId' => $client->id,
            'popName' => $client->pop->popname,
            'userId' => $client->userid,
            'clientName' => $customer->clients_name,
            'packageName' => $client->packages->package_name,
            'expiryDate' => $client->expire_date,
            'contactNo' => $customer->contact_no,
            'otherContact' => $customer->other_contact,
            'pendingTicket' => $tokenId,
            'connectionStatus' => $status ?? 'unknown',

        ];

        return response()->json([
            $data
        ], 200);
    }
}
