<?php

namespace App\Http\Controllers;

use App\Models\Package;
use App\Models\Subscription;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use PEAR2\Net\RouterOS;
use PEAR2\Net\RouterOS\Util;
use PEAR2\Net\RouterOS\Util as wifiUtil;
use PEAR2\Net\RouterOS\Client as wifiClient;
use App\Models\User;
use App\Models\Setting;
use Illuminate\Support\Facades\URL;
use App\Traits\Common;
use RouterOS\Query;
use RouterOS\Config;
use RouterOS\Client;
use App\Models\Wallet;
use App\Models\Message;
class PpoeController extends Controller
{
    use Common;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $profiles = [];
        $servers = [];
        $online = [];
        $error = [];
        if(Auth::user()->role == 3)
        {
            $users = User::where('role',2)->where('created_at', '>=', Carbon::now()->subMinutes(5))->orderBy('created_at', 'desc')->get();
        }
        if(Auth::user()->role == 1)
        {
            $users = User::where('role',2)->orderBy('created_at', 'desc')->get();

        }

        try {

            $profiles = $this->mkUtil()->setMenu('/ppp profile')->getAll();
            $online = $this->mkUtil()->setMenu('/ppp active')->getAll();
        } catch (Exception $e) {
            $error =  $e->getMessage();
        }

        return view('admin.users.ppoe.index',compact('online','error','profiles', 'users'));
    }
     public function PPoepackages()
    {
        $packages = Package::where('type','ppoe')->orderBy('created_at','DESC')->get();
        return view('admin.ppoe.index', compact('packages'));
    }

    public function create()
    {

        return view('admin.users.ppoe.create');
    }
     public function edit($id)
    {
        $user = User::where('id', $id)->first();
        return view('admin.users.ppoe.edit', compact('user'));
    }

    public function store(Request $request)
    {
        $route = URL('/admin/ppoe/users');

        $userData =  $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['required', 'string', 'unique:users'],
            'password' => ['required','min:4'],
            'package' => ['required'],
            'location' => ['required'],
             'region' => ['required']

        ]);
        $username = $request->phone;
        $password = $request->password;
        $profile = $request->package;
        $phone = $request->phone;



        $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/secret/add'))
                ->equal('name', $phone)
                ->equal('profile', $profile)
                ->equal('password', $password)
                ->equal('service', 'pppoe');

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

          //  dd($ok);

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

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'password' => Hash::make(1234),
            'role' => 2,
            'location' => $request->location,
             'region' => $request->region,

        ]);

         $sm = new Message;
        $message = "Dear $user->name welcome to swiftnet, to access your customer portal use https://billing.swiftnet.co.ke. Your login: $user->phone Your Password: 1234 Best Regards SWIFTNET.";
        $send = $sm->sendSms($user->phone, $message);

        //admin sms
        $admin = User::where('role',1)->first();
        $sm = new Message;
        $message2 = "Dear Admin a new user has been registered";
        $send = $sm->sendSms($admin->phone, $message2);

        $wallet = Wallet::create([
            'user_id' => $user->id,
            'amount' => '0.0'
        ]);
        $sub = Subscription::where('package',$request->package)->where('user_id',$user->id)->where('status',1)->first();
        $package = Package::where('name',$request->package)->first();

        if(!$sub)
        {
            $subscription = new Subscription();
            $subscription->username = $request->phone;
            $subscription->password = $request->password;
            $subscription->user_id = $user->id;
            $subscription->package = $package->id;
            $subscription->status = 1;
            $subscription->amount = $package->price;
             $subscription->start_date = now();
            $subscription->end_date = now()->addMonths(1);
            $subscription->save();
        }

        return redirect($route)->with('success','user created successfully');
    }
    public function update(Request $request,$id)
    {
        $route = URL('/admin/ppoe/users');

        $user = User::where('id',$id)->first();
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        $userData =  $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required'],
            'phone' => ['required'],
           // 'password' => ['required','min:4'],
            'package' => ['required'],
            'location' => ['required'],
            'start_date' => ['required'],
            'region' => ['required']
        ]);
        $username = $request->phone;
        $password = $request->password;
        $profile = $request->package;
        $phone = $request->phone;

        $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/secret/print'))
                ->where('name', $phone);
            $response = $client2->q($query)->read();


            foreach ($response as $res) {
                $userId = $res['.id'];
                $profile = $res['profile'];

                $editRequest = new RouterOS\Request('/ppp/secret/set');
                $editRequest->setArgument('.id', $res['.id']);
                $editRequest->setArgument('name', $phone);
               /// $editRequest->setArgument('password', $password);
                $editRequest->setArgument('profile', $profile);


                $editResponse = $client->sendSync($editRequest);
              //  dd($editResponse);
            }


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

        $user = User::where('id',$id)->update([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            //'password' => Hash::make($request->password),
            'role' => 2,
             'location' => $request->location,
             'region' => $request->region,

        ]);
        $sub = Subscription::where('package',$request->package)->where('user_id',$id)->where('status',1)->first();
        $package = Package::where('name',$request->package)->first();



         $currentDateTime =  \Carbon\Carbon::now();
         $specificDateTime = $currentDateTime->format('Y-m-d H:i:s');

        $dateTime = \Carbon\Carbon::parse($specificDateTime);

        // Format only the time part
        $formattedDateTime = $dateTime->format('H:i:s');


       //  $start_date = $request->start_date.' '.$formattedDateTime;

        $carbonDate = Carbon::createFromFormat('d/m/Y H:i', $request->start_date);

        // Format the date as 'Y-m-d H:i:s'
        $formattedDateTime = $carbonDate->format('Y-m-d H:i:s');


        $originalDateTime = \Carbon\Carbon::parse($formattedDateTime);

        $modifiedDateTime = $originalDateTime->addDays(31);

        $end_date =  $modifiedDateTime->format('Y-m-d H:i:s');


        $up =  Subscription::where('user_id',$id)->update([
            'username' => $username,
            // 'password' => Hash::make($request->password),
            'package' => $package->id,
            'amount' => $package->price,
            'start_date' => $formattedDateTime,
            'end_date' => $end_date,
        ]);

        if(!$sub)
        {
            $subscription = new Subscription();
            $subscription->username = $request->phone;
            $subscription->password = 1234;
            $subscription->user_id = $id;
            $subscription->package = $package->id;
            $subscription->status = 1;
            $subscription->amount = $package->price;
             $subscription->start_date = now();
            $subscription->end_date = now()->addMonths(1);
            $subscription->save();
        }

        return redirect($route)->with('success','user updated successfully');
    }
    public function delete(Request $request,$id)
    {
        $user = User::where('id',$id)->first();
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        $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/secret/print'))
                ->where('name', $user->phone);
            $response = $client2->q($query)->read();


            foreach ($response as $res) {
                $userId = $res['.id'];
                $query2 = (new Query('/ppp/active/remove'))
                ->equal('.id', $userId);

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

            }




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


        $up =  Subscription::where('user_id',$user->id)->update([
            'status' => 0
        ]);
        $user = User::where('id',$id)->delete();

        return redirect()->back()->with('success','user removed successfully');
    }
    public function deactivate(Request $request,$id)
    {
        $user = User::where('id',$id)->first();
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        $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/secret/print'))
                ->where('name', $user->phone);
            $response = $client2->q($query)->read();

           foreach ($response as $res) {
                $userId = $res['.id'];


                $editRequest = new RouterOS\Request('/ppp/secret/set');
                $editRequest->setArgument('.id', $res['.id']);

                $editRequest->setArgument('disabled', 'yes');


                $editResponse = $client->sendSync($editRequest);
              //  dd($editResponse);
            }


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

       User::where('id',$id)->update([
            'status' => 0
        ]);
        Subscription::where('user_id',$user->id)->update([
            'status' => 0
        ]);

        return redirect()->back()->with('success','user deactivated successfully');
    }
    public function activate(Request $request,$id)
    {
        $user = User::where('id',$id)->first();
        $sub = Subscription::where('user_id',$id)->first();

        $password = $user->password;
        $profile = $sub->package;
        $phone = $user->phone;
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        $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/secret/print'))
                ->where('name', $user->phone);
            $response = $client2->q($query)->read();

           foreach ($response as $res) {
                $userId = $res['.id'];


                $editRequest = new RouterOS\Request('/ppp/secret/set');
                $editRequest->setArgument('.id', $res['.id']);

                $editRequest->setArgument('disabled', 'no');


                $editResponse = $client->sendSync($editRequest);
              //  dd($editResponse);
            }


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

        User::where('id',$id)->update([
            'status' => 1
        ]);


            $subscription = new Subscription();
            $subscription->username = $phone;
            $subscription->password = $user->password;
            $subscription->user_id = $user->id;
            $subscription->package = $profile;
            $subscription->status = 1;
            $subscription->amount = $sub->amount;
            $subscription->start_date = now();
            $subscription->end_date = now()->addMonths(1);
            $subscription->save();


        return redirect()->back()->with('success','user activated successfully');
    }




}
