<?php

namespace App\Http\Controllers;

use App\Helpers\Helper;
use App\Models\Pricing;
use App\Models\User;
use App\Models\UserPackage;
use App\Services\PackageActivationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserPackageController extends Controller
{
    use Helper;

    public function __construct()
    {
        $this->model = new UserPackage();
    }

    /**
     * Get active package subscription for logged in user.
     */
    public function getActivePackage(Request $request): JsonResponse
    {
        $user = $request->user();
        $activePackage = PackageActivationService::getUserActivePackage($user);

        return response()->json([
            'status' => 2000,
            'success' => true,
            'data' => [
                'has_active_package' => $activePackage !== null,
                'package' => $activePackage,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'masking_rate' => $user->masking_rate,
                    'non_masking_rate' => $user->non_masking_rate,
                ],
            ],
        ]);
    }

    /**
     * User's package subscription history.
     */
    public function getHistory(Request $request): JsonResponse
    {
        $userId = $request->user()->id;
        $packages = UserPackage::where('user_id', $userId)
            ->with('package:id,title,type,billing_type')
            ->orderBy('id', 'desc')
            ->paginate($request->input('perPage', 15));

        return response()->json([
            'status' => 2000,
            'data' => $packages,
        ]);
    }

    /**
     * Admin: List all user package subscriptions.
     */
    public function index(Request $request)
    {
        $keyword = $request->input('keyword');
        $userId = $request->input('user_id');
        $status = $request->input('status');

        $data = UserPackage::with(['user:id,name,email,contact_number', 'package:id,title,type,billing_type'])
            ->when($keyword, function ($query) use ($keyword) {
                $query->whereHas('user', function ($q) use ($keyword) {
                    $q->where('name', 'LIKE', "%{$keyword}%")
                      ->orWhere('email', 'LIKE', "%{$keyword}%");
                })->orWhere('package_name', 'LIKE', "%{$keyword}%");
            })
            ->when($userId, function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->when($status !== null && $status !== '', function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->orderBy('id', 'desc')
            ->paginate($request->input('perPage', $this->perPage));

        return returnData(2000, $data);
    }

    /**
     * Admin: Manually activate / assign package to a user.
     */
    public function assign(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'package_id' => 'required|exists:pricings,id',
            'total_sms' => 'nullable|integer',
            'daily_limit' => 'nullable|integer',
            'expire_date' => 'nullable|date',
        ]);

        $user = User::findOrFail($validated['user_id']);
        $package = Pricing::findOrFail($validated['package_id']);

        $userPackage = PackageActivationService::activatePackageForUser(
            $user,
            $package,
            null,
            $validated
        );

        return response()->json([
            'status' => 2000,
            'success' => true,
            'message' => "Package '{$package->title}' activated successfully for {$user->name}.",
            'data' => $userPackage,
        ]);
    }
}
