<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Jobs\SubPackageEditJob;
use App\Models\Client;
use App\Models\Packages;
use App\Models\Pop;
use App\Models\Reseller;
use App\Models\SubPackage;
use Facade\Ignition\Support\Packagist\Package;
use Illuminate\Http\Request;

class SubPackageController extends Controller
{

    public function __construct()
    {

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

    }

    public function fetchPackage($id)
    {


        $reseller = Reseller::find($id);
        $list = explode(',', $reseller->package_list);
        if ($list) {
            foreach ($list as $a) {
                $packages[] = Packages::find($a);
            }
        }else{
            $packages[]='';
        }

        $data = [
            'Packages' => $packages,
        ];

        return $data;
    }

    public function index()
    {
        $permissions = userPermissions();

        // Build columns array for DataTables
        $columns = [
            ['data' => 0, 'name' => 'id'],
            ['data' => 1, 'name' => 'name'],
        ];
        $colIndex = 2;

        if (in_array('show-sub-package-rate', $permissions) || in_array('specific_management_services', $permissions)) {
            $columns[] = ['data' => $colIndex++, 'name' => 'rate'];
        }

        if ((in_array('show-sub-package-rate', $permissions) || in_array('specific_management_services', $permissions))
            && checkSettings('ResellerClientOnlineRecharge') == 'enable'
            && checkSettings('setClientPaymentAmountToClient') != 'enable') {
            $columns[] = ['data' => $colIndex++, 'name' => 'client_payment_amount'];
        }

        if (in_array('show-mother-package', $permissions)) {
            $columns[] = ['data' => $colIndex++, 'name' => 'reseller_name'];
        }

        if (in_array('show-mother-package', $permissions)) {
            $columns[] = ['data' => $colIndex++, 'name' => 'package_name'];
        }

        if (in_array('show-motherpackage-rate', $permissions)) {
            $columns[] = ['data' => $colIndex++, 'name' => 'package_rate'];
        }

        if (in_array('sub-pack-commission', $permissions)) {
            $columns[] = ['data' => $colIndex++, 'name' => 'commission'];
        }

        $columns[] = ['data' => $colIndex, 'name' => 'actions', 'orderable' => false, 'searchable' => false];

        return view('sub_package.index', [
            'page_title' => 'Sub Package List',
            'permissions' => $permissions,
            'columns' => $columns
        ]);
    }

    public function ajaxList(Request $request)
    {
        $sub_packages = SubPackage::conditionalList();
        $permissions = userPermissions();

        $data = [];
        foreach ($sub_packages as $r) {
            $row = [];
            $row[] = $r->id;
            $row[] = $r->name ?? '';

            // Package Rate
            if (in_array('show-sub-package-rate', $permissions) || in_array('specific_management_services', $permissions)) {
                $row[] = $r->rate ?? '';
            }

            // Client payment amount
            if ((in_array('show-sub-package-rate', $permissions) || in_array('specific_management_services', $permissions))
                && checkSettings('ResellerClientOnlineRecharge') == 'enable'
                && checkSettings('setClientPaymentAmountToClient') != 'enable') {
                $row[] = $r->client_payment_amount ?? '';
            }

            // Manager Name
            if (in_array('show-mother-package', $permissions)) {
                $row[] = $r->reseller->name ?? '';
            }

            // Mother Package
            if (in_array('show-mother-package', $permissions)) {
                $row[] = $r->package->package_name ?? '';
            }

            // Mother Package Rate
            if (in_array('show-motherpackage-rate', $permissions)) {
                $row[] = $r->package->package_rate ?? '';
            }

            // Commission
            if (in_array('sub-pack-commission', $permissions)) {
                $row[] = $r->commission ?? '';
            }

            // Actions
            $actions = '';
            if (in_array('sub-package_edit', $permissions)) {
                $actions .= '<a href="' . route('sub-packages.edit', $r->id) . '" class="btn btn-primary">Edit</a> ';
            }
            if (in_array('sub-package_destroy', $permissions)) {
                // Use JS-based confirmation to avoid double prompts
                $actions .= '<form action="' . route('sub-packages.destroy', $r->id) . '" method="POST" class="float-right pl-2 d-inline delete-subpackage-form">
                    ' . csrf_field() . '
                    ' . method_field('DELETE') . '
                    <button class="btn btn-info">Delete</button>
                </form> ';
            }
            if (in_array('view-sub-package-log-history', $permissions)) {
                $actions .= '<a href="' . route('editLog-history', ['id' => $r->id, 'type' => 'Sub-Package']) . '" class="btn btn-primary pull-right">History</a>';
            }
            $row[] = '<div class="whitespace-nowrap text-right text-sm font-medium">' . $actions . '</div>';

            $data[] = $row;
        }

        return response()->json([
            'data' => $data
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        return view('sub_package.create', [
            'resellers' => Reseller::resellerList()->get(),
            'packages' => Packages::all(),
            'page_title' => 'Add Sub Package'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //dd($request->all());

        $this->validate(
            $request,
            [
                'name' => 'required|unique:sub_packages,name',
                'rate' => 'required',
            ],
        );

        SubPackage::create([
            'name' => $request->name,
            'rate' => $request->rate,
            'reseller_id' => $request->reseller_id,
            'package_id' => $request->package_id,
            'commission' => $request->commission ?? 0,
            'client_payment_amount' => $request->client_payment_amount ?? 0,
            'created_by' => auth()->user()->id

        ]);

        return redirect()->route('sub-packages.index')->with('success_message', 'Sub Package Added Successufll');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $sp = SubPackage::find($id);

        $resellers = Reseller::resellerList()->get();

        $reseller = Reseller::where('id', $sp->reseller_id)->first();

        $list = explode(',', $reseller->package_list);
        if ($list) {
            foreach ($list as $a) {

                $package = Packages::find($a);

                if($package){
                    $packages[] = $package;
                }
            }
        } else {
            $packages[] = '';
        }

        return view('sub_package.update', [
            'sub_packages' => $sp,
            'packages' => $packages,
            'page_title' => 'Update Sub Package Information',
            'resellers' => $resellers
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate(
            $request,
            [
                'name' => 'required|unique:sub_packages,name,' . $id,
                'rate' => 'required',
            ]
        );

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

        $sub_package = SubPackage::find($id);
        $prvious_sub_package = $sub_package->id;
        $prvious_mother_package = $sub_package->package_id;

        $sub_package->update($request->all());
        if($prvious_mother_package != $request->package_id && $request->package_id != null){
            $clients = Client::with('pop', 'customerAccount', 'pop.reseller', "pop.nas")->where('sub_package_id', $prvious_sub_package)->get();
                SubPackageEditJob::dispatch($clients, $request->package_id);
        }

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

        $request->session()->flash('success_message', 'SubPackage Update Successfully Done');
        return redirect()->route('sub-packages.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $sub_package_in_pop = Pop::where('sub_package_list', 'like', '%' . $id . '%')->get();
        if($sub_package_in_pop){
            foreach($sub_package_in_pop as $package){
                $sub_pack_list = explode(',', $sub_package_in_pop[0]->sub_package_list);
                $key = in_array($id, $sub_pack_list);
                if($key){
                    return redirect()->route('sub-packages.index')->with('error_message', 'This Sub Package is assign in pop. So you can not delete it.');
                }
            }
        }

        $client_of_this_sub_package = Client::where('sub_package_id', $id)->get();
        if($client_of_this_sub_package->count() > 0){
            return redirect()->route('sub-packages.index')->with('error_message', 'This Sub Package is in use. So you can not delete it.');
        }else{
            $sp = SubPackage::find($id);
            $sp->delete();
            session()->flash('success_message', 'SubPackage Delete Successfully Done');
            return redirect()->route('sub-packages.index');
        }
    }
}
