<?php

namespace App\Http\Controllers;

use App\Models\Blog;
use App\Models\User;
use App\Models\Market;
use App\Models\Bid;
use App\Models\Sell;
use App\Models\Transaction;
use App\Models\Product;
use App\Models\Ownership;
use App\Models\Vendor;
use App\Models\VendorProduct;
use App\Models\Grant;
use App\Models\Plan;
use App\Models\SiteDetail;
use App\Models\Investment;
use App\Models\Withdrawal;
use App\Models\Deposit;
use App\Services\PaymentService;
use Illuminate\Support\Str;

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

class PagesController extends Controller
{
    public function __construct()
    {
        $this->middleware(['activated', '2fa'])->except(['welcome', 'addStore', 'storeSetup', 'setupPayment', 'setupInfo', 'expectation']);
    }

    public function welcome()
    {
        $products = Product::where('status', 1)->inRandomOrder()->paginate(32);

        return view('welcome', compact('products'));
    }

    public function addStore()
    {
        return view('auth.add-store');
    }

    public function storeSetup()
    {
        $activeDeposit = Deposit::where('user_id', auth()->user()->id)->where('type', 'setup')->where('status', null)->first();

        $completedDeposit = Deposit::where('user_id', auth()->user()->id)->where('type', 'setup')->where('status', 1)->first();

        if (isset($activeDeposit)) {
            return redirect()->route('setup-info', $activeDeposit->id);
        }

        if (isset($completedDeposit) && auth()->user()->activated) {
            return redirect()->route('home');
        }

        return view('auth.store-setup');
    }

    public function setupPayment(Request $request)
    {
        $response = PaymentService::pay();

        if (isset($response['error'])) {
            return redirect()->route('store-setup')->with('error', ucfirst($request->currency) . ' not available currently! Try another payment method.');
        }

        return redirect()->route('setup-info', $response['deposit']['id']);
    }

    public function setupInfo(Deposit $deposit)
    {
        $pay_info = PaymentService::payInfo($deposit);

        $deposit = Deposit::find($pay_info['deposit']['id']);

        if ($deposit->status == 1) {
            return redirect()->route('home')->with('message', 'Congratulations, your C2C store has been setup and you can now begin trading on the platform. A welcome mail has been sent to your email, do check it out!');
        }

        // dd($pay_info['payment']);

        return view('auth.setup-info', compact('pay_info', 'deposit'));
    }

    public function setupMade(Deposit $deposit)
    {
        $pay_info = PaymentService::payInfo($deposit);

        if (auth()->user()->activated) {
            return redirect()->route('home')->with('message', 'Congratulations, your C2C store has been setup and you can now begin trading on the platform. A welcome mail has been sent to your email, do check it out!');
        }

        if ($pay_info['payment']['payment_status'] == 'finished') {
            return redirect()->route('home')->with('message', 'Congratulations, your C2C store has been setup and you can now begin trading on the platform. A welcome mail has been sent to your email, do check it out!');
        }

        if ($pay_info['payment']['payment_status'] == 'partially_paid') {
            $percent = 15 / 100 * $pay_info['payment']['price_amount'];
            $sum = $pay_info['payment']['price_amount'] - $percent;
            if ($pay_info['payment']['actually_paid'] >= $sum) {
                return redirect()->route('home')->with('message', 'Congratulations, your C2C store has been setup and you can now begin trading on the platform. A welcome mail has been sent to your email, do check it out!');
            } else {
                return redirect()->route('setup-info', $deposit->id)->with('error', 'Your payment has been canceled, please try again.');
            }
            return redirect()->route('setup-info', $deposit->id)->with('message', 'Congratulations, your deposit has been approved and your main wallet has been funded with the amount you transferred.');
        }

        if ($pay_info['payment']['payment_status'] == 'waiting') {
            return redirect()->route('setup-info', $deposit->id)->with('message', 'Payment confirmations takes 10 minutes to process, please be patient while we confirm your payment.');
        }

        if ($pay_info['payment']['payment_status'] == 'expired') {
            return redirect()->route('setup-info', $deposit->id)->with('error', 'Your payment has expired, please try again.');
        }

        if ($pay_info['payment']['payment_status'] == 'failed') {
            return redirect()->route('setup-info', $deposit->id)->with('error', 'Your payment has been canceled, please try again.');
        }

        return view('payment_info', compact('pay_info', 'deposit'));
    }

    public function expectation()
    {
        return view('auth.expectation');
    }

    public function kyc()
    {
        return view('kyc');
    }

    public function products()
    {
        $products = Product::orderBy('id', 'desc')->take(20)->get();

        return view('products.index', compact('products'));
    }

    public function bidMarkets()
    {
        $markets = Market::where('type', 'bid')->get();

        return view('bid-markets', compact('markets'));
    }

    public function sellMarkets($ownership)
    {
        $markets = Market::where('type', 'sell')->get();

        $ownership = Ownership::where('slug', $ownership)->first();
        if($ownership == null) {
            abort(404);
        }

        return view('sell-markets', compact('markets', 'ownership'));
    }

    public function sellDetails($ownership, $market)
    {
        $market = Market::where('name', $market)->first();

        $ownership = Ownership::with('product')->where('slug', $ownership)->first();
        if($ownership == null) {
            abort(404);
        }

        $product = $ownership->product;

        $sell = Sell::where('ownership_id', $ownership->id)->where('status', 0)->first();

        return view('sell-details', compact('market', 'ownership', 'product', 'sell'));
    }

    public function marketplace($slug, $market)
    {
        // Single query with eager loading
        $market = Market::where('slug', $slug)->firstOrFail();

        $query = request()->search;

        $products = Product::with(['market:id,name,image']) // Only load needed columns
            ->where('market_id', $market->id)
            ->where('status', 1)
            ->when($query, function ($queryBuilder) use ($query) {
                $queryBuilder->where('name', 'like', "%$query%");
            })
            ->select('id', 'slug', 'name', 'image1', 'value', 'old_value', 'rating', 'market_id') // Only select needed columns
            ->inRandomOrder()
            ->paginate(48);

        // Cache markets list (they don't change often)
        $markets = Cache::remember('bid_markets', 3600, function () {
            return Market::where('type', 'bid')
                ->select('id', 'slug', 'name')
                ->get();
        });

        return view('marketplace', compact('products', 'market', 'markets'));
    }

    public function productDetails($slug)
    {
        $product = Product::with('market')->where('slug', $slug)->first();

        $bids = Bid::where('product_id', $product->id)
            ->where('status', 0)
            ->get();

        return view('product-details', compact('product', 'bids'));
    }

    public function category($category)
    {
        $query = request()->search;

        if (isset($query)) {
            $products = Product::with('market')
                ->where('category', $category)
                ->where('name', 'like', "%$query%")
                ->where('status', 1)
                ->inRandomOrder()->paginate(32);
        } else {
            $products = Product::with('market')
                ->where('category', $category)
                ->where('status', 1)
                ->inRandomOrder()->paginate(32);
        }

        return view('categories', compact('products', 'category'));
    }

    public function aiPlans()
    {
        $plans = Plan::all();

        return view('ai-plans', compact('plans'));
    }

    public function aiPurchase($plan)
    {
        $plan = Plan::where('name', $plan)->first();

        return view('ai-purchase', compact('plan'));
    }

    public function aiDashboard()
    {
        $investments = Investment::where('user_id', auth()->user()->id)->whereIn('status', [2, 3])->get();

        $ownerships = Ownership::where('id', auth()->user()->id)->where('type', 'ai')->get();

        return view('ai-dashboard', compact('investments', 'ownerships'));
    }

    public function aiActivity($investment, $name)
    {
        $plan = Plan::where('name', $name)->first();

        $investment = Investment::where('id', $investment)->where('plan_id', $plan->id)->first();

        $ownerships = $investment->ownerships()->take(50)->get();

        $bids = $investment->bids()->orderBy('created_at', 'desc')->take(100)->get();

        $sells = $investment->sells()->orderBy('created_at', 'desc')->take(100)->get();

        return view('ai-activity', compact('investment', 'sells', 'bids', 'ownerships'));
    }

    public function aiFund(Investment $investment)
    {
        if ($investment->funded) {
            return redirect()->route('ai-dashboard')->with('error', 'You cannot fund this AI Bot more than once!');
        }
        return view('fund-ai', compact('investment'));
    }

    public function aiWithdraw(Investment $investment)
    {
        if ($investment->balance < 1) {
            return redirect()->route('ai-dashboard')->with('error', 'You do not have enough funds to withdraw!');
        }

        return view('ai-withdraw', compact('investment'));
    }

    public function vendorApply()
    {
        // dd(session('error'));
        return view('vendor-apply');
    }

    public function addVendorProducts()
    {
        return view('add-vendor-products');
    }

    public function vendorDashboard()
    {
        if (auth()->user()->vendor()->doesntExist()) {
            return redirect()->route('vendor-apply')->with('error', 'You need to apply to access a vendor dashboard!');
        }

        $vendor = Vendor::where('user_id', auth()->user()->id)->first();

        return view('vendor-dashboard', compact('vendor'));
    }

    public function sendProduct(VendorProduct $product)
    {
        return view('send-product', compact('product'));
    }

    public function agentForm()
    {
        return view('agent-form');
    }

    public function affiliateProductDetails($slug)
    {
        $product = Product::where('slug', $slug)->first();

        return view('affiliate-product-details', compact('product'));
    }

    public function grantApply()
    {
        return view('grant-apply');
    }

    public function grants()
    {
        $grants = Grant::where('user_id', auth()->user()->id)->orderBy('id', 'desc')->get();

        return view('grants', compact('grants'));
    }
    
    public function ictpWithdrawPage()
    {
        return view('ictp-withdraw');
    }
}
