<?php

namespace App\Http\Controllers;

use App\Models\Amount;
use App\Models\Numbers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class SmsController extends Controller
{
    public function index()
    {
        $response = Http::get('https://onlinesim.io/api/getTariffs.php', [
            'apikey' => '04b9bdc115f56885e91181404e52ce2c',
            'lang' => 'en',
        ]);
        $countries = $response['countries'];
        $services = $response['services'];

        $getNumbers = Numbers::whereUserId(auth()->id())->latest()->get();
        $prices = Amount::latest()->get();

        $numbers = $getNumbers;
        return view(
            'dashboard',
            compact('countries', 'services', 'numbers', 'prices')
        );
    }

    public function getNumber(Request $request)
    {
        $response = Http::get('https://onlinesim.io/api/getNum.php', [
            'apikey' => '04b9bdc115f56885e91181404e52ce2c',
            'service' => $request->service,
            'country' => $request->country,
            'number' => true
        ]);
        $purchase = Numbers::create([
            'number' => $response['number'],
            'tzid' => $response['tzid'],
            'country' => $response['country'],
            'user_id' => auth()->id(),
        ]);

        if ($purchase) {
            return back()->with('success', 'Number purchased successfully');
        } else {
            return back()->with('error', 'Error getting number');
        }
    }

    public function getMessagePage()
    {
        $getUserNumber = Numbers::whereUserId(auth()->id())->latest()->get();
        $numbers = $getUserNumber;
        return view('messages', compact('numbers'));
    }

    public function getMessage(Request $request)
    {

        $response = Http::get('https://onlinesim.io/api/getState.php', [
            'apikey' => '04b9bdc115f56885e91181404e52ce2c',
            'tzid' => (int) $request->tzid,
            'message_to_code' => 0,
        ]);
        if (empty($response[0]['response'])) {
            return back()->with('error', 'No message or Number has expired');
        }
        if ($response[0]['response'] == 'TZ_NUM_ANSWER') {
            $data = $response[0]['msg'];
            return back()->with('message', $data);
        } else {
            return back()->with('error', 'No message or Number has expired');
        }
    }
}
