<?php

namespace App\Http\Controllers;

use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use PEAR2\Net\RouterOS;
use Exception;

class SubscriptionController extends Controller
{
    //
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function subscribe()
    {
        $host = env('MIKROTIK_HOST');
        $user = env('MIKROTIK_USERNAME');
        $pass = env('MIKROTIK_PASSWORD');
         try {
             $client = new RouterOS\Client($host,$user,$pass);

             $bronze = 'bronze';
             $gold = 'gold';
             $diamond = 'diamond';
             $amount = 5;
             $user = Auth::user();
             $phone = $user->phone;
             $formatted_phone = str_replace(' ','',$phone);

             $add_user = new RouterOS\Request('/tool/user-manager/user/add');

             //create user on raduis server
             $client->sendSync(
                 $add_user
                 ->setArgument('customer','admin')
                 ->setArgument('disabled','no')
                 ->setArgument('username',$formatted_phone)
                 ->setArgument('password',$formatted_phone)
                 ->setArgument('shared-users',1)

             );

             //activate user profile
             $activate_profile = new RouterOS\Request('/tool user-manager user create-activate-profile');
             $client->sendSync(
                 $activate_profile->setArgument('customer','admin')
                 ->setArgument('profile',$diamond)
                 ->setArgument('numbers',$formatted_phone)

             );
             $sub = Subscription::where('package',$diamond)->where('user_id',Auth::user()->id)->where('status',1)->first();
             if(!$sub)
             {
                 $subscription = new Subscription();
                 $subscription->username = $formatted_phone;
                 $subscription->password = $formatted_phone;
                 $subscription->user_id = Auth::user()->id;
                 $subscription->package = $diamond;
                 $subscription->status = 1;
                 $subscription->amount = $amount;
                 $subscription->save();
             }

             return redirect('/dashboard');


         }catch (Exception $e)
         {
             throw $e;
         }
    }
}
