<?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()
    {
        $sub_packages = SubPackage::conditionalList();
        $permissions = userPermissions();

         //dd($sub_packages);

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

    /**
     * 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',
                '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)
    {

        // dd($request->all());
        $this->validate(
            $request,
            [
                'name' => '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');
        }
    }
}
