<?php 
namespace App\Http\Controllers;
use App\Models\Package;


use Illuminate\Http\Request;
use App\Models\Client;
use DB;

class PackageController extends Controller
{
    // public function index(){
    //     return view('package');
    // }


    public function index($page_number)
    {
        // TODO: Implement index method
        // render the view
        $page_size = 30;
        $total_packages = DB::select("select count(*) as count from packages");
        $total_packages = $total_packages[0]->count;

        // $clients = Client::orderBy('created_at', 'desc')->paginate(10);
        // $clients = $clients->reverse();
       
        $total_pages = $this->calculateTotalPages($total_packages, $page_size);

        $offset = ($page_number - 1) * $page_size;
        $packages = DB::table('packages')->offset($offset)->limit($page_size)->get();

        $data = [
            'page_number' => $page_number,
            'total_pages' => $total_pages,
            'packages' => $packages
        ];

        // dd($packages);

        return view('package', $data);
    }

    // public function addPackage(Request $request)
    // {
    //     // return response()->json($request->all());
    //     // Capture the request data
    //     $data = [
    //         'data_package' => $request->input('dataPackage'),
    //         'price' => $request->input('price'),
    //         'package_type' => $request->input('packageType'),
    //     ];

    //     // Create a new package
    //     $package = new Package($data);

    //     // Save the package
    //     $package->save();

    //     // Return the package data as a JSON response
    //     return response()->json($package);
    // }
    public function addPackage(Request $request)
    {
        try {
            // Capture the request data
            $data = [
                'data_package' => $request->input('dataPackage'),
                'price' => $request->input('price'),
                'package_type' => $request->input('packageType'),
            ];


            // Check if the package already exists
            $existingPackage = Package::where(['data_package'=>$request->input('dataPackage')])->first();

            if ($existingPackage) {
                // Package already exists, throw an exception or handle accordingly
                throw new \Exception('Package already exists.');
            }

            // Create a new package
            $package = Package::create($data);

            // Return the package data as a JSON response
            return response()->json($package);
        } catch (QueryException $e) {
            // Handle database query exception
            return response()->json(['error' => 'Failed to add package.'], 500);
        } catch (\Exception $e) {
            // Handle other exceptions (e.g., package already exists)
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    public function calculateTotalPages($total_size, $pageSize) {
        return ceil($total_size / $pageSize);
    }

    public function edit($id)
    {
        $package = Package::find($id);

        if (!$package) {
            return response()->json(['message' => 'Client not found'], 404);
        }

        return response()->json($package);
    }

     public function update(Request $request, $id)
    {
        // return response()->json($request->all());

        // TODO: Implement update method
        $package = Package::find($id);

         $data = [
            'data_package' => $request->input('dataPackage'),
            'price' => $request->input('price'),
            'package_type' => $request->input('plan'),
        ];

        $package->update($data);
    }

    public function deletePackages(Request $request)
    {
        try {
            // Get the array of package IDs from the request
            $packageIds = $request->input('packages');

            // Delete the packages
            Package::whereIn('id', $packageIds)->delete();

            // Return a success response
            return response()->json(['message' => 'Packages deleted successfully.']);
        } catch (\Exception $e) {
            // Handle exceptions (e.g., package not found)
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    public function searchPlans(Request $request){
        // return response()->json($request->all());
        $search = $request->input('search');
        $packages = Package::where('data_package', 'like', "%$search%")
            ->orWhere('price', 'like', "%$search%")
            ->orWhere('package_type', 'like', "%$search%")
            ->get();

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