<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\Api\AuthApiController;
use App\Http\Controllers\Api\ProductApiController;
use App\Http\Controllers\Api\CategoryApiController;
use App\Http\Controllers\Api\CartApiController;
use App\Http\Controllers\Api\CheckoutApiController;
use App\Http\Controllers\Api\DashboardApiController;
use App\Http\Controllers\Api\HomeApiController;
use App\Http\Controllers\Api\SiteSettingsController;
use App\Http\Controllers\Api\LandingPageApiController;
use App\Http\Controllers\Api\ResellerApiController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
*/

// Public Authentication Routes
Route::post('/login', [AuthApiController::class, 'login']);
Route::post('/register', [AuthApiController::class, 'register']);
Route::post('/otp/send', [AuthApiController::class, 'sendOtp']);
Route::post('/otp/verify', [AuthApiController::class, 'verifyOtp']);
Route::post('/password/forgot', [AuthApiController::class, 'forgotPassword']);
Route::post('/password/reset', [AuthApiController::class, 'resetPassword']);

// Public Product & Category Routes
Route::get('/products', [ProductApiController::class, 'index']);
Route::get('/products/{id}', [ProductApiController::class, 'show']);
Route::get('/categories', [CategoryApiController::class, 'index']);
Route::get('/home-data', [HomeApiController::class, 'index']);
Route::get('/site-settings', [SiteSettingsController::class, 'index']);
Route::get('/shop-filters', [ProductApiController::class, 'shopFilters']);
Route::get('/reseller-packages', function () {
    $packages = \App\Models\ResellerPackage::where('is_active', true)->get()->map(function ($package) {
        $data = $package->toArray();
        $data['duration_days'] = $package->validity_days;
        return $data;
    });
    return response()->json([
        'success' => true,
        'data' => $packages,
    ]);
});

Route::post('/reseller/check-login', function (\Illuminate\Http\Request $request) {
    $credentials = $request->only('email', 'password');
    if (!\Illuminate\Support\Facades\Auth::attempt($credentials)) {
        return response()->json([
            'success' => false,
            'message' => 'ইমেইল অথবা পাসওয়ার্ডটি সঠিক নয়।',
        ], 422);
    }
    
    $user = \Illuminate\Support\Facades\Auth::user();
    if ($user->role !== 'reseller') {
        \Illuminate\Support\Facades\Auth::logout();
        return response()->json([
            'success' => false,
            'message' => 'দুঃখিত, আপনি রিসেলার হিসেবে নিবন্ধিত নন।',
        ], 403);
    }
    
    if ($user->reseller_status !== 'active') {
        $status = $user->reseller_status;
        \Illuminate\Support\Facades\Auth::logout();
        
        $statusMsg = match ($status) {
            'pending' => 'আপনার রিসেলার অ্যাকাউন্টটি এখনও অনুমোদনের অপেক্ষায় আছে। দয়া করে অ্যাডমিনের এপ্রুভালের জন্য অপেক্ষা করুন।',
            'expired' => 'আপনার রিসেলার মেম্বারশিপের মেয়াদ শেষ হয়ে গেছে। দয়া করে নবায়ন করুন।',
            'suspended' => 'আপনার রিসেলার অ্যাকাউন্টটি সাময়িকভাবে স্থগিত করা হয়েছে।',
            default => 'আপনার রিসেলার অ্যাকাউন্টটি সক্রিয় নয়।',
        };
        
        return response()->json([
            'success' => false,
            'message' => $statusMsg,
            'reseller_status' => $status,
        ], 403);
    }
    
    // Generate secure single-use token
    $token = \Illuminate\Support\Str::random(40);
    cache()->put("reseller_autologin_token_{$token}", $user->id, 60);

    \Illuminate\Support\Facades\Auth::logout();
    return response()->json([
        'success' => true,
        'message' => 'লগইন সফল হয়েছে। রিডাইরেক্ট করা হচ্ছে...',
        'redirect_url' => url("/reseller/autologin?token={$token}"),
    ]);
});

Route::post('/reseller/register', function (\Illuminate\Http\Request $request) {
    $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'phone' => 'required|string|min:11',
        'package_id' => 'required|exists:reseller_packages,id',
        'payment_method' => 'required|string',
        'sender_number' => 'nullable|string',
        'transaction_id' => 'required|string',
    ]);
    
    if ($validator->fails()) {
        return response()->json([
            'success' => false,
            'message' => $validator->errors()->first(),
        ], 422);
    }
    
    $user = \App\Models\User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password),
        'phone' => $request->phone,
        'role' => 'reseller',
        'reseller_status' => 'pending',
        'reseller_package_id' => $request->package_id,
    ]);
    
    $package = \App\Models\ResellerPackage::find($request->package_id);
    
    $description = "সদস্যপদ প্ল্যান ক্রয়: {$package->name} (মেথড: " . strtoupper($request->payment_method) . ", TxnID: {$request->transaction_id})";
    if ($request->filled('sender_number')) {
        $description = "সদস্যপদ প্ল্যান ক্রয়: {$package->name} (মেথড: " . strtoupper($request->payment_method) . ", Sender: {$request->sender_number}, TxnID: {$request->transaction_id})";
    }

    // Log pending transaction
    \App\Models\ResellerWalletTransaction::create([
        'user_id' => $user->id,
        'amount' => $package->price,
        'type' => 'debit',
        'status' => 'pending',
        'description' => $description,
    ]);
    
    return response()->json([
        'success' => true,
        'message' => 'নিবন্ধন সফল হয়েছে! আপনার পেমেন্ট ভেরিফাই করে অ্যাডমিন অ্যাকাউন্টটি সক্রিয় করে দেবেন। ধন্যবাদ।',
    ]);
});

// Public Landing Page Funnel Routes
Route::get('/landing-pages/{slug}', [LandingPageApiController::class, 'show']);
Route::post('/landing-pages/order', [LandingPageApiController::class, 'placeOrder']);

// Public Cart Routes (Uses session ID or X-Guest-Cart-Token header)
Route::get('/cart', [CartApiController::class, 'index']);
Route::post('/cart/add', [CartApiController::class, 'add']);
Route::post('/cart/update', [CartApiController::class, 'update']);
Route::post('/cart/remove', [CartApiController::class, 'remove']);
Route::post('/cart/clear', [CartApiController::class, 'clear']);

// Public Checkout/Location Info
Route::get('/divisions', [CheckoutApiController::class, 'divisions']);
Route::get('/districts', [CheckoutApiController::class, 'allDistricts']);
Route::get('/districts/{divisionId}', [CheckoutApiController::class, 'districts']);
Route::get('/upazilas/{districtId}', [CheckoutApiController::class, 'upazilas']);
Route::post('/coupon/apply', [CheckoutApiController::class, 'applyCoupon']);
Route::post('/shipping-methods', [CheckoutApiController::class, 'shippingMethods']);
Route::post('/checkout', [CheckoutApiController::class, 'placeOrder']);
Route::get('/orders/track', [CheckoutApiController::class, 'trackOrder']);

// Authenticated Routes (Laravel Sanctum SPA / Bearer Token)
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', [AuthApiController::class, 'user']);
    Route::post('/logout', [AuthApiController::class, 'logout']);
    
    // Dashboard / History
    Route::get('/dashboard/orders', [DashboardApiController::class, 'orders']);
    Route::get('/dashboard/orders/{id}', [DashboardApiController::class, 'orderDetails']);
    Route::get('/dashboard/coupons', [DashboardApiController::class, 'coupons']);
    Route::get('/dashboard/payments', [DashboardApiController::class, 'payments']);
    Route::get('/dashboard/reviews', [DashboardApiController::class, 'reviews']);
    Route::post('/reviews', [DashboardApiController::class, 'submitReview']);
    Route::get('/dashboard/tickets', [DashboardApiController::class, 'tickets']);
    Route::post('/dashboard/tickets', [DashboardApiController::class, 'submitTicket']);
    Route::post('/dashboard/addresses', [DashboardApiController::class, 'saveAddress']);
    Route::delete('/dashboard/addresses/{id}', [DashboardApiController::class, 'deleteAddress']);
    
    // Profile Updates
    Route::post('/dashboard/profile', [DashboardApiController::class, 'updateProfile']);
    Route::post('/dashboard/profile/phone', [DashboardApiController::class, 'updatePhone']);
    Route::post('/dashboard/profile/email', [DashboardApiController::class, 'updateEmail']);
    Route::post('/dashboard/profile/social-revoke', [DashboardApiController::class, 'revokeSocial']);
    Route::delete('/user/delete', [AuthApiController::class, 'deleteAccount']);

    // Reseller Portal Endpoints
    Route::prefix('reseller')->group(function () {
        Route::get('/stats', [ResellerApiController::class, 'resellerStats']);
        Route::post('/payment-settings', [ResellerApiController::class, 'updatePaymentSettings']);
        Route::get('/products', [ResellerApiController::class, 'resellerProducts']);
        Route::post('/orders', [ResellerApiController::class, 'placeResellerOrder']);
        Route::get('/orders', [ResellerApiController::class, 'resellerOrders']);
        Route::get('/orders/{orderNumber}', [ResellerApiController::class, 'resellerOrderDetail']);
        Route::get('/wallet-transactions', [ResellerApiController::class, 'walletTransactions']);
        Route::get('/withdraws', [ResellerApiController::class, 'withdrawRequests']);
        Route::post('/withdraws', [ResellerApiController::class, 'storeWithdrawRequest']);
        Route::post('/packages/purchase', [ResellerApiController::class, 'purchasePackage']);
        Route::post('/profile', [ResellerApiController::class, 'updateProfile']);
        Route::post('/shipping-cost', [ResellerApiController::class, 'shippingCostByDistrict']);
        Route::get('/community-groups', [ResellerApiController::class, 'communityGroups']);
    });
});

