<?php

namespace App\Http\Controllers;

use App\Models\Package;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use PEAR2\Net\RouterOS;
use App\Traits\Common;
use RouterOS\Query;
use RouterOS\Config;
use RouterOS\Client;


class PackagesController extends Controller
{
    use Common;


    public function __construct()
    {
        $this->middleware('auth');
    }
    public function createPackage()
    {
        return view('admin.hotspot.create');

    }
    public function storePackage(Request $request)
    {
        $packageData =  $request->validate([
            'name' => ['required', 'string', 'max:255','unique:packages'],
            'type' => ['required'],
            'size' => ['required', 'string'],
            'price' => ['required'],
            'unit' => ['required'],
            'time' => ['required'],
            'devices' => ['required'],
            'upload_speed' => ['required'],
            'download_speed' => ['required'],
            'description' => ['required']
        ]);

        if($request->input('unit') == 'Minutes')
        {
            $time = $request->input('time') * 60;


        }elseif ($request->input('unit') == 'Hours') {
             $time = $request->input('time') * 3600;

        }elseif ($request->input('unit') == 'Days') {
             $time = $request->input('time') * 86400;

        }elseif ($request->input('unit') == 'Months') {
             $time = $request->input('time') * 2629746;

        }


        $profileName = $request->input('name');
        $uploadLimit = $request->input('upload_speed');
        $downloadLimit = $request->input('download_speed');
        $dataLimit = $request->input('size');
        $maxDevices = $request->input('devices');
        $timeLimit = $time;
        $type = $request->input('type');
        $description = $request->input('description');

        $connect = $this->connect();

        $config = new Config([
            'host' => $connect['host'] ,
            'user' => $connect['username'],
            'pass' => $connect['password'],
            'port' => $connect['port'],
        ]);

        $client = new Client($config);

        if($type == 'hotspot'){

            $dataSizeBytes = $dataLimit * 1024 * 1024;

            $query = (new Query('/ip/hotspot/user/profile/add'))
                ->equal('name', $profileName)
                ->equal('idle-timeout', '00:05:00')
                ->equal('rate-limit', $uploadLimit.'k/'.$downloadLimit.'k')
                ->equal('shared-users',$maxDevices )
                ->equal('session-timeout',$time);
               // ->equal('limit-byte', $dataSizeBytes);


           try{
             $response = $client->q($query)->read();

             Package::create($packageData);

           }catch(\Exeption $e)
           {

           }
        }


        return redirect()->back()->with('success','package created successfully');

    }

    public function editPackage($id)
    {
        $package = Package::where('id',$id)->first();



        if(!$package)
        {
            return redirect()->back()->with('error', 'Package not found');
        }
        return view('admin.hotspot.edit', compact('package'));
    }
    public function updatePackage($id,Request $request)
    {

        $package = Package::where('id',$id)->first();
        if(!$package)
        {
            return redirect()->back()->with('error', 'Package not found');
        }
        $packageData =  $request->validate([
            'name' => ['required', 'string', 'max:255','unique:packages'],
            'type' => ['required',],
            'size' => ['required', 'string'],
            'price' => ['required'],
            'unit' => ['required'],
            'time' => ['required'],
            'devices' => ['required'],
            'upload_speed' => ['required'],
            'download_speed' => ['required'],
             'description' => ['required']
        ]);

        if($request->input('unit') == 'Minutes')
        {
            $packageData['time'] = $request->input('time') * 60;


        }elseif ($request->input('unit') == 'Hours') {
             $packageData['time'] = $request->input('time') * 3600;

        }elseif ($request->input('unit') == 'Days') {
              $packageData['time'] = $request->input('time') * 86400;

        }elseif ($request->input('unit') == 'Months') {
              $packageData['time'] = $request->input('time') * 2629746;

        }

        $profileName = $request->input('name');
        $uploadLimit = $request->input('upload_speed');
        $downloadLimit = $request->input('download_speed');
        $dataLimit = $request->input('size');
        $maxDevices = $request->input('devices');
        $timeLimit = $packageData['time'];
        $type = $request->input('type');
        $description = $request->input('description');

        $connect = $this->connect();

        $config = new Config([
            'host' => $connect['host'] ,
            'user' => $connect['username'],
            'pass' => $connect['password'],
            'port' => $connect['port'],
        ]);

        $client = new Client($config);
         $client2 = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);

        if($type == 'hotspot'){

            $dataSizeBytes = $dataLimit * 1024 * 1024;

            $query = (new Query('/ip/hotspot/user/profile/print'))
            ->where('name',$package->name);

            if($package->type == 'hotspot')
            {
                $route = URL('/packages/hotspot');

            }else{
                $route = URL('/packages/hotspot');

            }
           try{

             $response = $client->q($query)->read();
              foreach ($response as $resp) {

                $editRequest = new RouterOS\Request('/ip/hotspot/user/profile/set');
                $editRequest->setArgument('.id', $resp['.id']);
                $editRequest->setArgument('name', $profileName);
                $editRequest->setArgument('idle-timeout', '00:05:00');
                $editRequest->setArgument('rate-limit', $uploadLimit.'M/'.$downloadLimit.'M');
                $editRequest->setArgument('session-timeout',$timeLimit);
                $editRequest->setArgument('shared-users',$maxDevices);


                $editResponse = $client2->sendSync($editRequest);

                if ($editResponse->getType() !== RouterOS\Response::TYPE_FINAL) {
                    return redirect()->back()
                        ->with('error', 'Failed to update package: ' . $editResponse->getProperty('message'));

                }

               }

           }catch(\Exeption $e)
           {
             return redirect($route)->with('error','Failed something went wrong');

           }

            $package = Package::where('id',$id)->update($packageData);
                return redirect($route)->with('success','success');

        }
    }




    public function deletePackage($id)
    {
        $package = Package::where('id',$id)->first();
        if(!$package)
        {
            return redirect()->back()->with('error', 'Package not found');
        }

        if($package->type == 'hotspot')
        {
            $route = URL('packages/hotspot');

        }else{
            $route = URL('packages/hotspot');

        }

        //delete mikrotik

          $connect = $this->connect();

            $config = new Config([
                'host' => $connect['host'] ,
                'user' => $connect['username'],
                'pass' => $connect['password'],
                'port' => $connect['port'],
            ]);

            $client = new Client($config);
             $client2 = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);

            if($package->type == 'hotspot'){
                try {
                    $query = (new Query('/ip/hotspot/user/profile/print'))
                        ->where('name',$package->name);

                     $response = $client->q($query)->read();
                      foreach ($response as $resp) {

                         $deleteRequest = new RouterOS\Request('/ip/hotspot/user/profile/remove');
                        $deleteRequest->setArgument('.id', $resp['.id']);


                        $deleteResponse = $client2->sendSync($deleteRequest);

                        if ($deleteResponse->getType() !== RouterOS\Response::TYPE_FINAL) {
                            // Handle user deletion failure
                            return redirect()->back()
                               ->with('error', 'Failed to delete Hotspot user: ' . $deleteResponse->getProperty('message'));
                        }
                    }



                } catch (Exception $e) {

                     return redirect($route)->with('error','something went wrong');

                }

                if($package->type == 'hotspot')
                {
                    $route = URL('/packages/hotspot');

                }else{
                    $route = URL('/packages/hotspot');

                }
            }
        if (!$package->delete()){
            return redirect($route)->with('error','something went wrong');

        }else{
            return redirect($route)->with('success','success');

        }
    }
    public function activatePackage($id)
    {
        $package = Package::where('id',$id)->first();
        if(!$package)
        {
            return redirect()->back()->with('error', 'Package not found');
        }

        if($package->type == 'hotspot')
        {
            $route = URL('packages/hotspot');

        }else{
            $route = URL('packages/hotspot');

        }

        $ok = Package::where('id',$id)->update([
            'status' => 1
        ]);
        if ($ok){
            return redirect($route)->with('success','success');

        }else{
            return redirect($route)->with('error','Something went wrong');

        }
    }
    public function deactivatePackage($id)
    {
        $package = Package::where('id',$id)->first();
        if(!$package)
        {
            return redirect()->back()->with('error', 'Package not found');
        }

        if($package->type == 'hotspot')
        {
            $route = URL('packages/hotspot');

        }else{
            $route = URL('packages/hotspot');

        }

        $ok = Package::where('id',$id)->update([
            'status' => 0
        ]);
        if ($ok){
            return redirect($route)->with('success','success');

        }else{
            return redirect($route)->with('error','Something went wrong');

        }
    }
    public function createPpoe()
    {
        $connect = $this->connect();
         $config = new Config([
            'host' => $connect['host'] ,
            'user' => $connect['username'],
            'pass' => $connect['password'],
            'port' => $connect['port'],
        ]);
        $client2 = new Client($config);
        $query = (new Query('/ip/pool/print'));

         $ipPools = $client2->query($query)->read();
       
        return view('admin.ppoe.create',compact('ipPools'));
    }

    public function editPpoe($id,Request $request)
    {
        $package = Package::where('id', $id)->first();
         $connect = $this->connect();
         $config = new Config([
            'host' => $connect['host'] ,
            'user' => $connect['username'],
            'pass' => $connect['password'],
            'port' => $connect['port'],
        ]);
        $client2 = new Client($config);
        $query = (new Query('/ip/pool/print'));
         $ipPools = $client2->query($query)->read();

        return view('admin.ppoe.edit',compact('package','ipPools'));
    }


    public function storePPoePackage(Request $request)
    {

        $route = URL('packages/ppoe');
        $packageData =  $request->validate([
            'name' => 'required|string|unique:packages,name',
            'price' => 'required',
           // 'time' => 'required',
            //'unit' => 'required',
           // 'speed' => 'required',
            'type' => 'required',
            'local_address' => 'required',
            'remote_address' => 'required',
          //   'upload_speed' => ['required'],
          //  'download_speed' => ['required'],
            'rate_limit' => ['required']

        ]);


        $connect = $this->connect();
        $client = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);
        $config = new Config([
            'host' => $connect['host'] ,
            'user' => $connect['username'],
            'pass' => $connect['password'],
             'port' => $connect['port'],
        ]);

        $client2 = new Client($config);


        // Create a new PPPoE profile
        try{
            $query = (new Query('/ppp/profile/print'))
                ->where('name', $packageData['name']);

            $response = $client2->q($query)->read();

            $count = count($response);
            if ($count == 0) {

               $query = (new Query('/ppp/profile/add'))
                ->equal('name', $request->name)
                ->equal('local-address', $request->local_address)
                ->equal('remote-address', $request->remote_address)
                ->equal('rate-limit',$request->rate_limit);

            $response = $client2->q($query)->read();

               $package = Package::create($packageData);

            }


        }catch (\Exception $e){
            dd($e);
        }

        if (!$package){
            return redirect($route)->with('error','something went wrong');

        }else{
            return redirect($route)->with('success','success');

        }

      }



    public function editPPoePackage(Request $request, $id)
    {

        $route = URL('packages/ppoe');
        $pck = Package::where('id', $id)->first();

        $packageData = $request->validate([
            'name' => 'required',
            'price' => 'required',
           // 'time' => 'required',
            //'speed' => 'required',
            'local_address' => 'required',
            'remote_address' => 'required',
            'type' => 'required',
            // 'upload_speed' => ['required'],
           // 'download_speed' => ['required'],
            'rate_limit' => ['required']


        ]);



        $connect = $this->connect();
        $client = new RouterOS\Client($connect['host'], $connect['username'], $connect['password'],$connect['port']);
        $config = new Config([
            'host' => $connect['host'],
            'user' => $connect['username'],
            'pass' => $connect['password'],
             'port' => $connect['port'],
        ]);

        $client2 = new Client($config);

        try {
            $query = (new Query('/ppp/profile/print'))
                ->where('name', $pck->name);

            $response = $client2->q($query)->read();


             foreach ($response as $resp) {

                $editRequest = new RouterOS\Request('/ppp/profile/set');
                $editRequest->setArgument('.id', $resp['.id']);
                $editRequest->setArgument('name', $request->name);
                $editRequest->setArgument('local-address', $request->input('local_address'));
                $editRequest->setArgument('rate-limit',$request->rate_limit);
                $editRequest->setArgument('remote-address',$request->input('remote_address'));

                $editResponse = $client->sendSync($editRequest);

            }


        } catch (\Exception $e) {
            dd($e);
        }

        $package= Package::where('id',$id)->update($packageData);

        if (!$package) {
            return redirect($route)->with('error', 'something went wrong');

        } else {
            return redirect($route)->with('success', 'success');

        }
    }
    public function deletePPoePackage(Request $request, $id)
    {
        $route = URL('packages/ppoe');
        $pck = Package::where('id', $id)->first();

        $connect = $this->connect();
        $client = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);
        $config = new Config([
            'host' => $connect['host'] ,
            'user' => $connect['username'],
            'pass' => $connect['password'],
            'port' => $connect['port'],
        ]);

        $client2 = new Client($config);

        try{
            $query = (new Query('/ppp/profile/print'))
                ->where('name', $pck->name);

            $response = $client2->q($query)->read();

            $count = count($response);
            foreach ($response as $resp) {

                $removeRequest = new RouterOS\Request('/ppp/profile/remove');
                $removeRequest->setArgument('.id', $resp['.id']);
                $editResponse = $client->sendSync($removeRequest);

                $client->sendSync($removeRequest);

            }


        }catch (\Exception $e){
            dd($e);
        }

        if (!$pck->delete()){
            return redirect($route)->with('error','something went wrong');

        }else{
            return redirect($route)->with('success','PPPoE package removed successfully');

        }

    }









}
