<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\DataPlanRequest;
use App\Models\DataPlan;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class DataPlanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $dataPlansQuery = DataPlan::query();

// Handle search filter
        if ($request->filled('search')) {
            $searchTerm = $request->input('search');
            $dataPlansQuery->where('network', 'like', '%' . $searchTerm . '%')->orWhere('pname', 'like', '%' . $searchTerm . '%');

        }

// Handle status filter
        if ($request->filled('network')) {
            $dataPlansQuery->where('network', $request->input('network'));
        }
$dataPlans = $dataPlansQuery->paginate(10);

        return view('admin.data-plan.index', compact('dataPlans'))
            ->with('i', ($request->input('page', 1) - 1) * $dataPlans->perPage());
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $dataPlan = new DataPlan();

        return view('admin.data-plan.create', compact('dataPlan'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(DataPlanRequest $request): RedirectResponse
    {
        DataPlan::create($request->validated());

        return Redirect::route('admin.data-plans.index')
            ->with('success', 'DataPlan created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show($id): View
    {
        $dataPlan = DataPlan::find($id);

        return view('admin.data-plan.show', compact('dataPlan'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id): View
    {
        $dataPlan = DataPlan::find($id);

        return view('admin.data-plan.edit', compact('dataPlan'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(DataPlanRequest $request, DataPlan $dataPlan): RedirectResponse
    {
        $dataPlan->update($request->validated());

        return Redirect::route('admin.data-plans.index')
            ->with('success', 'DataPlan updated successfully');
    }

    public function destroy($id): RedirectResponse
    {
        DataPlan::find($id)->delete();

        return Redirect::route('admin.data-plans.index')
            ->with('success', 'DataPlan deleted successfully');
    }
}
