<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Models\Packages;
use App\Models\SubPackage;
use App\Models\Pop;
use App\Models\Reseller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PackagesController extends Controller
{
    public function __construct()
    {

        $this->middleware('permission:package_index|package_create|package_edit|package_destroy|specific_management_services', ['only' => ['index', 'show']]);
        $this->middleware('permission:package_create', ['only' => ['create', 'store']]);
        $this->middleware('permission:package_edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:package_destroy', ['only' => ['destroy']]);


        $this->middleware('permission:sub-package-permission', ['only' => ['permissionUpdate']]);
        $this->middleware('permission:sub-package-permission-form|specific_management_services', ['only' => ['subPackagePermission']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $list = Packages::conditionalList();
        $resellers = Reseller::get();

        return view('packages.index', [
            'page_title' => 'Packages List',
            'list' => $list,
            'resellers' => $resellers,
            'url' => route('packages.create'),
            // 'add_button' => 'true',
            'class' => 'text-white bg-blue-600',
            'value' => 'Add New Package'
        ]);
    }


    public function create()
    {
        return view('packages.create', [
            'page_title' => 'Add New Packages'
        ]);
    }


    public function store(Request $request)
    {
        $this->validate($request, [
            'package_name'  => checkAPI() ? 'required|unique:packages,package_name' : '',
            'package_rate'  => 'required',
            'pool_name'     => checkAPI() ? '' : 'required',
        ]);

        DB::beginTransaction();

        try {

            $package_id = Packages::create([
                'package_name'  => trim($request->package_name),
                'package_rate' => trim($request->package_rate),
                'pool_name'     => checkAPI() ? $request->profile_name : $request->pool_name,
                'commission'     => $request->commission ?? 0,
                'profile_name'     => checkAPI() ? $request->profile_name : $request->pool_name,
                'speed_up'     => $request->speed_up ?? '0',
                'speed_down'     => $request->speed_down ?? '0',
                'limite_quantity'     => $request->limite_quantity,
                'package_bandwidth'     => $request->package_bandwidth,
                'btrc_package_price'    => $request->btrc_package_price ?? 0.00,
                'client_payment_amount'    => $request->client_payment_amount ?? 0,
            ])->id;

            if (!checkAPI()) {
                DB::table('radgroupcheck')->insert([
                    [
                        'groupname' => $package_id,
                        'attribute' => 'Framed-Protocol',
                        'op'        => '==',
                        'value'     => 'PPP'
                    ],
                    [
                        'groupname' => $package_id,
                        'attribute' => 'Simultaneous-Use',
                        'op'        => ':=',
                        'value'     => 1
                    ]
                ]);

                DB::table('radgroupreply')->insert([
                    'groupname' => $package_id,
                    'attribute' => 'Framed-Pool',
                    'op'        => '=',
                    'value'     => $request->pool_name
                ]);
            }

            DB::commit();

            Toastr::success('Packages Added successfull', 'Success');
            return redirect()->back(); //route('packages.index');
        } catch (\Exception $e) {
            DB::rollback();
            // $request->session()->flash('error_message', 'Something wrong');
            Toastr::error('Something wrong', 'Error');
        }
    }


    public function show(Packages $packages)
    {
        //
    }


    public function edit($id)
    {
        $list = Packages::find($id);
        return view('packages.update', [
            'page_title' => 'Edit Packages List',
            'list' => $list
        ]);
    }


    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'package_name'  => 'required|unique:packages,package_name,' . $id,
            'package_rate'  => 'required',
            'pool_name'     => checkAPI() ? '' : 'required',
            'profile_name'  => checkAPI() ? 'required' : '',

        ]);



        DB::beginTransaction();

        try {

            $type = 'Package';
            $old_info = Packages::where('id', $id)->first();

            Packages::where('id', $id)
                ->update([
                    'package_name'  => $request->package_name,
                    'package_rate'  => $request->package_rate,
                    'pool_name'     => checkAPI() ? $request->profile_name : $request->pool_name,
                    'commission'    => $request->commission ?? 0,
                    'profile_name'  => checkAPI() ? $request->profile_name : $request->pool_name,
                    'speed_up'     => $request->speed_up ?? '0',
                    'speed_down'     => $request->speed_down ?? '0',
                    'limite_quantity'     => $request->limite_quantity,
                    'package_bandwidth'     => $request->package_bandwidth,
                    'btrc_package_price'    => $request->btrc_package_price ?? 0.00,
                    'client_payment_amount'    => $request->client_payment_amount ?? 0.00,
                ]);

            $new_info = Packages::find($old_info->id);
            (new EditLogHistory)->editLogSave($old_info, $type, $old_info, $new_info);

            if (!checkAPI()) {
                DB::table('radgroupreply')
                    ->where('groupname', $id)
                    ->update([
                        'value'     => $request->pool_name
                    ]);
            }

            DB::commit();

            // $request->session()->flash('success_message', 'Packages Update successfull');
            Toastr::success('Packages Update successfull', 'Success');
            return redirect()->route('packages.index');
        } catch (\Exception $e) {
            DB::rollback();
            // $request->session()->flash('error_message', 'Something wrong');
            Toastr::error('Something wrong', 'Error');
        }
    }


    public function destroy($id)
    {
        $package_in_reseller = Reseller::where('package_list', 'like', '%' . $id . '%')->get();
        if ($package_in_reseller) {
            foreach ($package_in_reseller as $reseller) {
                $package_list = explode(',', $reseller->package_list);
                $key = in_array($id, $package_list);
                if ($key) {
                    Toastr::error('This package is in use by reseller', 'Error');
                    return redirect()->back();
                }
            }
        }
        $package_in_sub_package = SubPackage::where('package_id', $id)->first();
        if ($package_in_sub_package) {
            Toastr::error('This package is in use by sub package', 'Error');
            return redirect()->back();
        }
        $package_in_clients = DB::table('clients')->where('package_id', $id)->get()->count();
        if ($package_in_clients > 0) {
            Toastr::error('This package is in use by clients', 'Error');
            return redirect()->back();
        }

        Packages::where('id', $id)->delete();
        Toastr::success('Packages Delete successfull', 'Success');
        return redirect()->back();
    }

    public function subPackagePermission($id)
    {


        $pop = Pop::find($id);
        $allPackage = SubPackage::where('reseller_id', $pop->reseller_id)->get();
        return view('pop.package', [
            'pop' => $pop,
            'packages' => $allPackage,
            'page_title' => 'Assign Sub Package Permission'
        ]);
    }
    public function permissionUpdate(Request $request)
    {

        $this->validate($request, [
            'reseller_id' => 'required'
        ]);



        try {

            if (isset($request->package_id) && !empty($request->package_id)) {
                $package_list = implode(',', $request->package_id);
            } else {
                $package_list = '';
            }

            $reseller = Pop::find($request->reseller_id);
            $reseller->sub_package_list = $package_list;
            $reseller->save();

            // return redirect()->route('sub_package_permission', $request->reseller_id)->with('success_message', 'Package Assigned Success');
            Toastr::success('Package Assigned Success', 'Success');
            return redirect()->route('sub_package_permission', $request->reseller_id);

            // }
        } catch (Exception $e) {

            // return redirect()->route('sub_package_permission', $request->reseller_id)
            //     ->with('error_message', 'Some Thing is wrong!!');
            Toastr::error('Some Thing is wrong!!', 'Error');
            return redirect()->route('sub_package_permission', $request->reseller_id);
        }
    }

    public function packageProfile(Request $request)
    {
        $tepm_package = Packages::find($request->package);
        return $tepm_package;
    }
}
