<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use App\Http\Services\PaymentServices;
use App\Models\User;
use App\Models\Setting;
use App\Models\UserLedger;
use App\Models\Withdrawal;
use App\Models\Purchase;
use App\Models\Deposit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class WithdrawController extends Controller
{
    /**
     * Display the main withdrawal page with clear logic checks.
     */
    public function withdraw()
    {
        $user = Auth::user();

        // 1. BANK DETAILS CHECK
        if ($user->gateway_method == null && $user->gateway_number == null) {
            return redirect()->route('user.card')->with('info', 'Please configure your bank details first.');
        }

        // 2. PRODUCT PURCHASE CHECK (The "Withdrawal Lock")
        // Checks if user has any active paid product
        $hasPurchased = Purchase::where('user_id', $user->id)
                        ->where('status', 'active')
                        ->where('amount', '>', 0)
                        ->exists();

        if (!$hasPurchased) {
            // User ko message milega ki product kharidna zaroori hai
            return redirect()->route('dashboard')->with('error', 'Withdrawal locked! You must purchase a product first to enable withdrawals.');
        }

        // 3. RECHARGE LOCK: Calculating only the income/profit
        $totalDeposit = Deposit::where('user_id', $user->id)
                        ->where('status', 'approved')
                        ->sum('amount');

        $withdrawable_balance = $user->balance - $totalDeposit;

        if ($withdrawable_balance < 0) {
            $withdrawable_balance = 0;
        }

        return view('app.main.withdraw.index', compact('withdrawable_balance'));
    }

    /**
     * Handle withdrawal request submission.
     */
    public function withdrawConfirmSubmit(Request $request, PaymentServices $payment)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:1'
        ]);

        if ($validator->fails()) {
            return back()->with('error', 'Please enter a valid withdrawal amount.');
        }

        $user = User::find(Auth::id());
        $setting = Setting::first();

        // Check if withdrawal service is open
        if ($setting->open_transfer != 1) {
            return back()->with('error', 'Withdrawal services are temporarily unavailable.');
        }

        // --- SECURITY VALIDATIONS ---

        // Verification 1: Must have a product
        $hasPurchased = Purchase::where('user_id', $user->id)
                        ->where('status', 'active')
                        ->where('amount', '>', 0)
                        ->exists();

        if (!$hasPurchased) {
            return back()->with('error', 'Action denied! You must purchase a product to withdraw your earnings.');
        }

        // Verification 2: Recharge amount cannot be withdrawn
        $totalDeposit = Deposit::where('user_id', $user->id)
                        ->where('status', 'approved')
                        ->sum('amount');
        
        $withdrawable_balance = $user->balance - $totalDeposit;

        if ($request->amount > $withdrawable_balance) {
            return back()->with('error', 'Note: You can only withdraw your profit (Income, Gifts, Tasks). Recharge amount is locked for product purchases only.');
        }

        // --- PROCEED WITH WITHDRAWAL ---

        $minWithdraw = setting('minimum_withdraw');
        $maxWithdraw = setting('maximum_withdraw');
        $taxRate = 6; 

        if ($request->amount < $minWithdraw) {
            return back()->with('error', 'Minimum withdrawal amount is Rs ' . number_format($minWithdraw));
        }

        if ($request->amount > $maxWithdraw) {
            return back()->with('error', 'Maximum withdrawal amount is Rs ' . number_format($maxWithdraw));
        }

        $charge = ($request->amount * $taxRate) / 100;
        $finalAmount = $request->amount - $charge;

        $debit = debit_user_wallet($user->id, 2, 'Rs', $request->amount);
        if ($debit['status'] == false) {
            return back()->with('error', $debit['message']);
        }

        $withdrawal = new Withdrawal();
        $withdrawal->user_id = $user->id;
        $withdrawal->method_name = 'Bank Transfer';
        $withdrawal->trx = rand(100000, 999999);
        $withdrawal->number = $user->gateway_number;
        $withdrawal->amount = $request->amount;
        $withdrawal->currency = 'Rs';
        $withdrawal->charge = $charge;
        $withdrawal->oid = 'WD-' . strtoupper(uniqid());
        $withdrawal->final_amount = $finalAmount;
        $withdrawal->status = 'pending';

        if ($withdrawal->save()) {
            $ledger = new UserLedger();
            $ledger->user_id = $user->id;
            $ledger->reason = 'Withdrawal Request';
            $ledger->perticulation = 'Withdrawal request for Rs ' . number_format($request->amount) . ' submitted.';
            $ledger->amount = $request->amount;
            $ledger->debit = $request->amount;
            $ledger->status = 'pending';
            $ledger->date = date('d-m-Y H:i');
            $ledger->save();
        }

        return back()->with('success', 'Your withdrawal request for Rs ' . number_format($request->amount) . ' has been submitted successfully.');
    }

    public function withdrawPreview()
    {
        $withdrawals = Withdrawal::where('user_id', Auth::id())->latest()->get();
        return view('app.main.withdraw.withdraw-preview', compact('withdrawals'));
    }
}
