<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\PackageModuleLink;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class PackageModuleLinkController extends Controller
{
    public function index(): JsonResponse
    {
        $packageModuleLinks = PackageModuleLink::with(['package', 'module'])->get();
        return response()->json(['data' => $packageModuleLinks], 200);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'PackageId' => 'required|exists:package_masters,PackageId',
            'ModuleID' => 'required|exists:module_master,ModuleID',
            'ModuleFixPrice' => 'required|numeric|min:0',
            'ModuleFreeUsers' => 'required|integer|min:0',
            'ExtraUserFees' => 'required|numeric|min:0',
            'MarginShare' => 'required|integer|min:0|max:100',
        ]);

        $packageModuleLink = PackageModuleLink::create($validated);
        return response()->json(['data' => $packageModuleLink, 'message' => 'Package Module Link created successfully'], 201);
    }

    public function show($id): JsonResponse
    {
        $packageModuleLink = PackageModuleLink::with(['package', 'module'])->findOrFail($id);
        return response()->json(['data' => $packageModuleLink], 200);
    }

    public function update(Request $request, $id): JsonResponse
    {
        $packageModuleLink = PackageModuleLink::findOrFail($id);
        $validated = $request->validate([
            'PackageId' => 'required|exists:package_masters,PackageId',
            'ModuleID' => 'required|exists:module_master,ModuleID',
            'ModuleFixPrice' => 'required|numeric|min:0',
            'ModuleFreeUsers' => 'required|integer|min:0',
            'ExtraUserFees' => 'required|numeric|min:0',
            'MarginShare' => 'required|integer|min:0|max:100',
        ]);

        $packageModuleLink->update($validated);
        return response()->json(['data' => $packageModuleLink, 'message' => 'Package Module Link updated successfully'], 200);
    }

    public function destroy($id): JsonResponse
    {
        $packageModuleLink = PackageModuleLink::findOrFail($id);
        $packageModuleLink->delete();
        return response()->json(['message' => 'Package Module Link deleted successfully'], 200);
    }
}
