<?php

namespace App\Http\Controllers;

use App\Models\Mpesa;
use App\Models\Package;
use App\Models\Setting;
use App\Models\Subscription;
use App\Models\User;
use App\Traits\Common;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\URL;
use PEAR2\Net\RouterOS;
use RouterOS\Query;
use RouterOS\Config;
use RouterOS\Client;

class HotspotController extends Controller
{
    use Common;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $profiles = [];
        $servers = [];
        $online = [];
        $error = [];

        $users = User::orderBy('created_at','DESC')->get();
        try {
            $profiles = $this->mkUtil()->setMenu('/ip hotspot user profile')->getAll();
            //total hotspots
            $servers = $this->mkUtil()->setMenu('/ip hotspot')->getAll();
            $online = count($this->mkUtil()->setMenu('/ip hotspot active')->getAll());



        } catch (Exception $e) {
            $data['error'] =  $e->getMessage();
        }

        return view('admin.users.hotspot.index', compact('profiles','servers','online','error','users'));


    }
    public function createProfile()
    {
        return view('admin.users.hotspot.create');

    }

    public function storeProfile(Request $request)
    {

        $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']
        ]);

        //send to mikrotik
        //dont hash mikrotik password
        $username = $request->phone;
        $password = $request->password;
        $profile = $request->package;
        try {
            // Create a RouterOS client
            $connect = $this->connect();
            $client = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);

            // Create a new Hotspot user
            $createRequest = new RouterOS\Request('/ip/hotspot/user/add');
            $createRequest->setArgument('name', $username);
            $createRequest->setArgument('password', $password);
            $createRequest->setArgument('profile', $profile);

            $createResponse = $client->sendSync($createRequest);

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




           //  $connect = $this->connect();

           //  $config = new Config([
           //      'host' => $connect['host'] ,
           //      'user' => $connect['username'],
           //      'pass' => isset($connect['password']) ? $password : "",
           //     // 'port' => $connect['port'],
           //  ]);
           //   $client = new Client($config);



           //  $query = (new Query('/ip/hotspot/active/add'))
           //      ->equal('user', $username)
           //      ->equal('profile',$profile);
           //     // ->equal('limit-byte', $dataSizeBytes);

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

           //   dd($response);

           // }catch(\Exeption $e)
           // {

           // }






            // Enable the Hotspot user's access
//             $activateRequest = new RouterOS\Request('/ip/hotspot/active/add');
//             $activateRequest->setArgument('name', $username);


//             $activateResponse = $client->sendSync($activateRequest);
//             dd($activateResponse);

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

//             // Success message or redirection
// //            return redirect()->route('hotspot.users')
// //                ->with('success', 'Hotspot user created, profile assigned, and activated successfully.');
        } catch (\Exception $e) {
            // Handle connection or other exceptions
            return redirect()->back()
                ->with('error', 'Failed to create, assign, and activate Hotspot user: ' . $e->getMessage());
        }

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

        $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 = $request->package;
            $subscription->status = 1;
            $subscription->amount = $package->price;
            $subscription->save();
        }


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

    }

    public function hotspotPackages()
    {
        $packages = Package::where('type','hotspot')->orderBy('created_at','DESC')->paginate(10);
        return view('admin.hotspot.index', compact('packages'));
    }


    public function editProfile($id)
    {
        $user = User::where('id',$id)->first();
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        $user = User::where('id',$id)->first();
        return view('admin.users.hotspot.edit', compact('user'));
    }

    public function updateProfile($id,Request $request)
    {
        $user = User::where('id',$id)->first();
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        $userData =  $request->validate([
            'name' => ['required', 'string'],
            'email' => 'required|string|email|max:255|unique:users,email,' . $id,
            'phone' => 'required|string|max:15|unique:users,phone,' . $id,
            'password' => ['required','min:4'],
            'package' => ['required']
        ]);

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

        try {
              $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']);



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

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


             foreach ($response as $resp) {

                $editRequest = new RouterOS\Request('/ip/hotspot/user/set');
                $editRequest->setArgument('.id', $resp['.id']);
                $editRequest->setArgument('name', $username);

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

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

                }
            }
        } catch (\Exception $e) {
            // Handle connection or other exceptions
            return redirect()->back()
                ->with('error', 'Failed to edit Hotspot user: ' . $e->getMessage());
        }

          $user = User::where('id',$id)->update([
        'name' => $request->name,
        'email' => $request->email,
        'phone' => $request->phone,
        'password' => Hash::make($request->password)
       ]);

        $sub = Subscription::where('package',$request->package)->where('user_id',$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 = $id;
            $subscription->package = $request->package;
            $subscription->status = 1;
            $subscription->amount = $package->price;
            $subscription->save();

        }else{
            Subscription::where('user_id',$id)->update([
            'username' => $request->phone,
            'password' =>$request->password,
            'user_id' => $id,
            'amount' => $package->price


        ]);
        }

        return redirect()->back()->with('success','profile updated successfully');
    }

    public function deleteProfile($id)
    {
        $user = User::where('id',$id)->first();
        if(!$user)
        {
            return redirect()->back()->with('error', 'user not found');
        }
        //remove from mikrotik
        try {
            $connect = $this->connect();
            $client2 = 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'],
            ]);

            $client = new Client($config);

            $query = (new Query('/ip/hotspot/user/print'))
                ->where('name', $user->phone);
            $response = $client->q($query)->read();

             foreach ($response as $resp) {

                 $deleteRequest = new RouterOS\Request('/ip/hotspot/user/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'));
                }


                if($user->delete())
                {
                Subscription::where('user_id', $id)->update([
                    'status'=>0
                ]);
                    return redirect()->back()->with('success', 'user deleted successfully');


                }else{

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

                }

             }




        } catch (\Exception $e) {
            // Handle connection or other exceptions
            return redirect()->route('hotspot-users.index')
                ->with('error', 'Failed to delete Hotspot user: ' . $e->getMessage());
        }


    }

     public function subscribeHotspot(Request $request,$packageId)
    {
        $packe = Package::where('id',$packageId)->first();
        $profile = $packe->name;
        $amount = $packe->amount;

        $phone = Auth::user()->phone;
        $username = Auth::user()->phone;
        $password = Auth::user()->password;

        // Create a RouterOS client
        $connect = $this->connect();
        $client = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);

        $mac = exec('getmac');
        $mac_array = explode(" ",$mac);
        $ip_address = $request->ip();


        $userData['ip_address'] = $ip_address;
        $createRequest = new RouterOS\Request('/ip/hotspot/user/add');
        $createRequest->setArgument('name', $phone);
        $createRequest->setArgument('profile', $profile);
        $createRequest->setArgument('address', $ip_address);
        $createRequest->setArgument('mac-address', $mac_array[0]);


        $createResponse = $client->sendSync($createRequest);

        if ($createResponse->getType() !== RouterOS\Response::TYPE_FINAL) {

                    // Handle user creation failure

            return redirect()->back()
                ->with('error', 'You are already subscribed to a package deplete the current packeage to subscribe again');

        }


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

        if(!$sub)
        {
            $subscription = new Subscription();
            $subscription->username = $phone;
            $subscription->password = $password;
            $subscription->user_id = Auth::user()->id;
            $subscription->package = $profile;
            $subscription->status = 1;
            $subscription->amount = $packe->price;
            $subscription->save();
        }
        // Success message or redirection
        return redirect()->back()
            ->with('success', 'Subscribed successfully Enjoy.');


    }

    public function subscribeHotspot1(Request $request,$packageId)
    {
        $packe = Package::where('id',$packageId)->first();
        $profile = $packe->name;
        $amount = $packe->amount;

        $phone = Auth::user()->phone;
        $username = Auth::user()->phone;
        $password = Auth::user()->password;
        $reference = 'WIFI PAYMENT';
        $p_data = new Mpesa;

        $response_data = $p_data->processPayment($amount,$phone,$reference);

        if($response_data['status'] == 0){
            $check_status = $p_data->stkPushStatus($response_data['checkoutId']);
            if($check_status){
                $data1 = json_decode($check_status, true);

                $status = $data1['ResultCode'];
                if($status ==0){

                    //store hotspot
                    try {
                        // Create a RouterOS client
                        $connect = $this->connect();
                        $client = new RouterOS\Client($connect['host'],$connect['username'],$connect['password'],$connect['port']);

                        // Create a new Hotspot user
                        $createRequest = new RouterOS\Request('/ip/hotspot/user/add');
                        $createRequest->setArgument('name', $phone);
                        $createRequest->setArgument('password', $password);

                        $createResponse = $client->sendSync($createRequest);

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

                        // Find the ID of the created Hotspot user
                        $userID = $createResponse->getProperty('.id');

                        // Assign the user to the specified Hotspot profile
                        $assignProfileRequest = new RouterOS\Request('/ip/hotspot/user/set');
                        $assignProfileRequest->setArgument('.id', $userID);
                        $assignProfileRequest->setArgument('profile', $profile);

                        $assignProfileResponse = $client->sendSync($assignProfileRequest);

                        if ($assignProfileResponse->getType() !== RouterOS\Response::TYPE_FINAL) {
                            // Handle profile assignment failure
                            return redirect()->back()
                                ->with('error', 'Failed to assign the Hotspot profile: ' . $assignProfileResponse->getProperty('message'));
                        }

                        // Enable the Hotspot user's access
                        $activateRequest = new RouterOS\Request('/ip/hotspot/active/add');
                        $activateRequest->setArgument('user', $username);

                        $activateResponse = $client->sendSync($activateRequest);

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

                        $sub = Subscription::where('package',$request->package)->where('user_id',Auth::routes()->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 = Auth::user()->id;
                            $subscription->package = $request->package;
                            $subscription->status = 1;
                            $subscription->amount = $package->price;
                            $subscription->save();
                        }
                        // Success message or redirection
                        return redirect()->route('hotspot.users')
                            ->with('success', 'Hotspot user created, profile assigned, and activated successfully.');
                    } catch (\Exception $e) {
                        // Handle connection or other exceptions
                        return redirect()->back()
                            ->with('error', 'Failed to create, assign, and activate Hotspot user: ' . $e->getMessage());
                    }
                    //insert subscription
                }else{
                    //return failed
                    return redirect()->back()
                        ->with('error', 'Failed Please Try Again');
                }
            }else{
                return redirect()->back()
                    ->with('error', 'Failed Please Try Again');
            }
        }else{
            return redirect()->back()
                ->with('error', 'Failed Please Try Again');
        }
        if ($response_data['status'] == 2){
            return redirect()->back()
                ->with('error', 'Failed Please Try Again');
        }
    }



}
