<?php

namespace App\Http\Controllers\User;

use App\Classes\GeniusMailer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\BankPlan;
use Auth;
use App\Models\Currency;
use App\Models\Generalsetting;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Withdraw;
use App\Models\WithdrawMethod;
use Illuminate\Support\Facades\Input;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Illuminate\Support\Str;
use Validator;

class WithdrawController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:web');
    }

  	public function index()
    {
        $data['withdraws'] = Withdraw::whereUserId(auth()->id())->orderBy('id','desc')->limit(6)->get();
        $data['methods'] = WithdrawMethod::whereStatus(1)->orderBy('id','desc')->get();
        return view('user.withdraw.index',$data);
    }

    public function history(Request $request){
        $data['withdraws'] = Withdraw::when($request->trx_no,function($query) use ($request){
                                        return $query->where('txnid', $request->trx_no);
                                    })
                                    ->when($request->type,function($query) use ($request){
                                        if($request->type != 'all'){
                                            return $query->where('status',$request->type);
                                        }else{

                                        }
                                    })
                                    ->whereUserId(auth()->id())->orderBy('id','desc')->paginate(10);
        return view('user.withdraw.history',$data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required|gt:0',
        ]);

        $user = auth()->user();
        $method = WithdrawMethod::whereId($request->method_id)->first();

        if($method->min_amount > $request->amount){
            return redirect()->back()->with('warning','Min Amount is '.$method->min_amount);
        }

        if($request->amount > $method->max_amount){
            return back()->with('warning','Max Amount is '.$method->max_amount);
        }

        $currency = Currency::whereId($method->currency_id)->first();
        $amountToDeduct = $request->amount/$currency->value;

        $fee = (($method->percentage / 100) * $request->amount) + $method->fixed;
        $fee = $fee/$currency->value;

        $finalamount = $amountToDeduct + $fee;

        if($request->withdraw_wallet == 'main_wallet'){
            if($finalamount > $user->balance){
                return redirect()->back()->with('warning','Insufficient Balance.');
            }
        }else{
            if($finalamount > $user->interest_balance){
                return redirect()->back()->with('warning','Insufficient Balance.');
            }
        }

        if($request->withdraw_wallet == 'main_wallet'){
            $user->balance = $user->balance - $finalamount;
        }else{
            $user->interest_balance = $user->interest_balance - $finalamount;
        }

        $user->update();

        $txnid = Str::random(12);
        $newwithdraw = new Withdraw();
        $newwithdraw['user_id'] = auth()->id();
        $newwithdraw['currency_id'] = $method->currency_id;
        $newwithdraw['method'] = $method->name;
        $newwithdraw['txnid'] = $txnid;
        $newwithdraw['amount'] = $amountToDeduct;
        $newwithdraw['fee'] = $fee;
        $newwithdraw['details'] = $request->details;
        $newwithdraw->save();

        $trans = new Transaction();
        $trans->email = $user->email;
        $trans->amount = $finalamount;
        $trans->type = "Payout";
        $trans->profit = "minus";
        $trans->txnid = $txnid;
        $trans->user_id = $user->id;
        $trans->save();

        $gs = Generalsetting::findOrFail(1);

        // $to = $user->email;
        $subject = 'Withdrawal Request Received';
        $msg = '<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Withdrawal Request Received</title>
                    <style>
                        body {
                            margin: 0;
                            padding: 0;
                            font-family: "Arial", sans-serif;
                            background-color: #f7f7f7;
                        }
                        .email-wrapper {
                            width: 100%;
                            background-color: #f7f7f7;
                            padding: 20px 0;
                        }
                        .email-content {
                            width: 100%;
                            max-width: 600px;
                            background-color: #ffffff;
                            border-radius: 8px;
                            margin: 0 auto;
                            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                        }
                        .email-header {
                            background-color: #003366;
                            padding: 20px;
                            text-align: center;
                            border-radius: 8px 8px 0 0;
                        }
                        .email-header img {
                            max-width: 200px;
                        }
                        .email-header span {
                            font-size: 18px;
                            font-weight: 600;
                            color: #00BFFF;
                            display: block;
                            margin-top: 10px;
                        }
                        .email-body {
                            padding: 16px 30px;
                            font-size: 16px;
                            line-height: 1.5;
                            color: #333;
                        }
                        .email-body h3 {
                            color: #003366;
                            margin-bottom: 15px;
                        }
                        .email-body p {
                            margin-bottom: 20px;
                        }
                        .email-button {
                            display: inline-block;
                            background-color: #003366;
                            color: #ffffff !important;
                            padding: 6px 12px;
                            font-size: 16px;
                            border-radius: 5px;
                            text-decoration: none;
                        }
                        .email-footer {
                            background-color: #1f1f1f;
                            color: #ffffff;
                            text-align: center;
                            padding: 12px;
                            border-radius: 0 0 8px 8px;
                            font-size: 14px;
                        }
                        .email-footer a {
                            color: #00BFFF;
                            text-decoration: none;
                        }
                    </style>
                </head>
                <body>
                
                <div class="email-wrapper">
                    <div class="email-content">
                        <div class="email-header">
                            <img src="https://fluxeassets.com/imgx/etemp.png" alt="Fluxe Assets Logo">
                            <span>Guiding You Toward Financial Growth</span>
                        </div>
                        <div class="email-body">
                            <p>Dear <strong>'.$user->name.'</strong>,</p>
                            <p>We have received your withdrawal request and it is currently being processed.</p>
                			<p>You will be notified once the payout is complete. If you have any questions, feel free to contact us at <a href="mailto:support@fluxeassets.com">support@fluxeassets.com</a>.</p>
                			<p>Thank you for choosing <strong>Fluxe Assets</strong>.</p>
                			<p style="margin-top: 30px;">Best regards,<br>The Fluxe Assets Team</p>
                			
                        </div>
                        <div class="email-footer">
                            <p>Copyright &copy; 2025 <a href="https://fluxeassets.com">Fluxe Assets</a>. All rights reserved.</p>
                        </div>
                    </div>
                </div>
                
                </body>
                </html>';

        if($gs->is_smtp == 1)
        {
            /*
            $data = [
                'to' => $user->email,
                'type' => "Withdraw",
                'cname' => $user->name,
                'oamount' => $newwithdraw->amount,
                'aname' => "",
                'aemail' => "",
                'wtitle' => "",
            ];

            $mailer = new GeniusMailer();
            $mailer->sendAutoMail($data);
            */
            
            $mail = new PHPMailer(true);
    
            try {
                // SMTP settings
                $mail->isSMTP();
                $mail->Host       = $gs->smtp_host;
                $mail->SMTPAuth   = true;
                $mail->Username   = $gs->smtp_user;
                $mail->Password   = $gs->smtp_pass;
                $mail->SMTPSecure = $gs->smtp_encryption; // 'tls' or 'ssl'
                $mail->Port       = $gs->smtp_port;
				$mail->CharSet = 'UTF-8';
    
                // Recipients
                $mail->setFrom($gs->from_email, $gs->from_name);
                $mail->addAddress($user->email, $user->name);
    
                // Content
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body    = $msg;
				
				$mail->send();
				
			} catch (Exception $e) {
			return response()->json('Email could not be sent. Error: ' . $mail->ErrorInfo);
			}            
        }
        else
        {
            $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
            mail($to,$subject,$msg,$headers);
        }

        return redirect()->route('user.withdraw.index')->with('message','Withdraw Requesting Successfully');

    }

    public function details(Request $request, $id){
        $data['data'] = Withdraw::findOrFail($id);

        return view('user.withdraw.details',$data);
    }
}
