<?php

namespace App\Http\Controllers\Api\Admin\Subscription;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Notification\StoreNotificationRequest;
use App\Http\Resources\Admin\AdvertismentResource;
use App\Http\Resources\Admin\GoogleAddIndexResource;
use App\Http\Resources\Admin\Notification\NotificationIndexResource;
use App\Http\Resources\Admin\SubscriptionIndexResource;
use App\Models\Advertisment;
use App\Models\GoogleAd;
use App\Models\Notification;
use App\Models\Subscription;
use App\Models\User;
use App\Support\FileUploader;
use App\Traits\ApiResponder;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class SubscriptionController extends Controller
{
    use ApiResponder;
    /**
     * Display a listing of the resource.
     */

    public function index()
    {
        $subscriptions = Subscription::orderBy('id', 'desc')->with('user')->paginate(15); // eager load user
        return $this->respondResource(SubscriptionIndexResource::collection($subscriptions));
    }

    // Show single subscription
    public function show(Subscription $subscription)
    {
        $subscription->load('user');
        return $this->respondResource(new SubscriptionIndexResource($subscription));
    }

    // Delete subscription
    public function destroy(Subscription $subscription)
    {
        $subscription->delete();
        return $this->respondWithSuccess('Subscription deleted successfully');
    }



    public function store(Request $request)
    {
        $request->validate([
            'email' => 'required|exists:users,email',
            'product_id' => 'nullable|string',
            'expires_at' => 'required|date|after:today',
        ]);

        $user = User::where('email', $request->email)->first();

        $subscription = Subscription::create([
            'user_id' => $user->id,
            'product_id' => $request->product_id,
            'platform' => $user->device_type ?? 'web',
            'purchase_token' => Str::uuid(),
            'expires_at' => $request->expires_at,
            'is_active' => 1,
            'is_by_admin' => 1,
            'raw_response' => json_encode([
                'source' => 'admin',
                'message' => 'Subscription added manually by admin'
            ]),
        ]);

        return $this->respondResource(new SubscriptionIndexResource($subscription), [
            'message' => 'Subscription added successfully'
        ]);
    }
}
