<?php
namespace App\Http\Controllers\API\Vendor;

use App\Http\Controllers\Controller;
use App\Models\Vendor;
use App\Models\SubscriptionTransaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class VendorProfileController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $vendor = $request->user()->vendor()->with('user:id,name,email,phone,avatar')->first();
        return response()->json(['vendor' => $vendor]);
    }

    public function update(Request $request): JsonResponse
    {
        $vendor = $request->user()->vendor;
        $data = $request->validate([
            'store_name'   => 'sometimes|string|max:255',
            'description'  => 'nullable|string',
            'phone'        => 'nullable|string|max:20',
            'address'      => 'nullable|string',
            'city'         => 'nullable|string',
            'state'        => 'nullable|string',
            'country'      => 'nullable|string',
            'postal_code'  => 'nullable|string',
            'social_links' => 'nullable|array',
            'logo'         => 'nullable|image|max:2048',
            'banner'       => 'nullable|image|max:5120',
            'bank_name'           => 'nullable|string',
            'bank_account_number' => 'nullable|string',
            'paypal_email'        => 'nullable|email',
        ]);

        if ($request->hasFile('logo')) {
            if ($vendor->logo) Storage::disk('public')->delete($vendor->logo);
            $data['logo'] = $request->file('logo')->store('vendors/logos', 'public');
        }
        if ($request->hasFile('banner')) {
            if ($vendor->banner) Storage::disk('public')->delete($vendor->banner);
            $data['banner'] = $request->file('banner')->store('vendors/banners', 'public');
        }

        $vendor->update($data);
        return response()->json(['message' => 'Profile updated.', 'vendor' => $vendor]);
    }

    public function registerStore(Request $request): JsonResponse
    {
        $user = $request->user();
        if ($user->vendor) {
            return response()->json(['message' => 'Store already registered.'], 422);
        }

        $data = $request->validate([
            'store_name'  => 'required|string|max:255',
            'description' => 'nullable|string',
            'phone'       => 'nullable|string',
        ]);

        $vendor = Vendor::create([
            ...$data,
            'user_id' => $user->id,
            'slug'    => Str::slug($data['store_name']) . '-' . Str::random(6),
            'status'  => 'pending',
        ]);

        return response()->json(['message' => 'Store registered. Awaiting admin approval.', 'vendor' => $vendor], 201);
    }

    public function subscription(Request $request): JsonResponse
    {
        $vendor = $request->user()->vendor;
        $transactions = $vendor->subscriptionTransactions()->latest()->get();
        return response()->json([
            'current_plan'        => $vendor->subscription_plan,
            'expires_at'          => $vendor->subscription_expires_at,
            'is_active'           => $vendor->hasActiveSubscription(),
            'max_products'        => $vendor->getMaxProducts(),
            'transactions'        => $transactions,
            'available_plans'     => config('vendorflow.plans'),
        ]);
    }

    public function upgradeSubscription(Request $request): JsonResponse
    {
        $vendor = $request->user()->vendor;
        $data = $request->validate([
            'plan'           => 'required|in:pro,agency',
            'payment_method' => 'required|in:stripe,paypal,card',
        ]);

        $plan = config("vendorflow.plans.{$data['plan']}");

        // Dummy payment processing — structure ready for real gateway
        $transaction = SubscriptionTransaction::create([
            'vendor_id'      => $vendor->id,
            'plan'           => $data['plan'],
            'amount'         => $plan['price'],
            'currency'       => 'USD',
            'payment_method' => $data['payment_method'],
            'transaction_id' => 'DUMMY-' . strtoupper(Str::random(12)),
            'status'         => 'completed',
            'starts_at'      => now(),
            'expires_at'     => now()->addDays($plan['duration_days']),
        ]);

        $vendor->update([
            'subscription_plan'       => $data['plan'],
            'subscription_expires_at' => $transaction->expires_at,
            'commission_rate'         => $plan['commission_rate'],
        ]);

        return response()->json(['message' => 'Subscription upgraded.', 'transaction' => $transaction]);
    }
}
