<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ProductTestPackage;
use App\Models\TestPackage;
use App\Models\Product;

class ProductTestPackagesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        $pages = isset($request->pages)?$request->pages:'';
        $data = ProductTestPackage::select([
                'product_test_packages.id',
                'product_test_packages.test_package_id',
                'product_test_packages.product_id',
                'test_packages.name',
                'test_packages.code',
                'test_packages.status',
            ])
            ->leftjoin('test_packages', function ($join) {
                $join->on('test_packages.id', '=', 'product_test_packages.test_package_id')
                ->whereNull('test_packages.deleted_at');
            })
            ->where('product_test_packages.product_id', $id);

        $product = Product::select('name')->where('id', $id)->first();

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('test_packages.name', 'like', '%'.$search_query.'%');
                })
                ->orderBy('product_test_packages.priority', 'ASC')
                ->paginate($sort_by);

            return view('product-test-packages.table', compact('data', 'product'));

        } else {
            $data = $data
                ->orderBy('product_test_packages.priority', 'ASC')
                ->paginate(10);
        }

        return view('product-test-packages.index', compact('data', 'id', 'product','pages'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $ids = ProductTestPackage::select([\DB::raw('GROUP_CONCAT(test_package_id SEPARATOR ",") AS ids')])->where('product_id', $id)->first();
        $ids = explode(',',$ids->ids);

        $tests = TestPackage::whereNotIn('id', $ids)->get();

        return view('product-test-packages.create', compact('tests'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'product_id' => 'required'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        foreach($request->test_item_id as $key => $value) {
            $data = [
                'test_package_id' => $value,
                'product_id'      => $request->product_id
            ];

            ProductTestPackage::create($data);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Test packages linked successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Test packages linked successfully');
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        ProductTestPackage::find($request->id)->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
            ]
        ]);
    }

    public function getSelectedTestPackages(Request $request)
    {
        if (isset($request->id) && !empty($request->id)) {
            $test_packages = TestPackage::select(['id','name'])->whereIn('id', $request->id)->get();

            $sno = 1;
            $row = '';
            foreach($test_packages as $package){

                $row .= '
                <tr>
                    <td>'. $sno++ .'</td>
                    <td>'. ucfirst($package->name) .'</td>
                    <td>
                        <a class="remove-btn itme_id btn-sm btn-danger" data-value="'. $package->id .'">
                        <i class="bi bi-trash-fill text-white"></i></a>
                    </td>
                </tr>';
            }

            return $row;
        }
    }

    public function reorder(Request $request)
    {
        foreach ($request->order as $order) {
            ProductTestPackage::where(['id' => $order['id']])->update(['priority' => $order['position']]);
        }

        return response()->json([
            'status' => true,
            'message' => ['Priority updated successfully'],
        ]);
    }
}
