<?php

namespace App\Http\Controllers\Admin;

use App\Classes\GeniusMailer;
use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\Deposit;
use App\Models\Generalsetting;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Datatables;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class DepositController extends Controller
{
    public function datatables()
    {
        $datas = Deposit::orderBy('id','desc');

        return Datatables::of($datas)
                        ->editColumn('created_at', function(Deposit $data) {
                            $date = date('d-m-Y',strtotime($data->created_at));
                            return $date;
                        })
                        ->addColumn('customer_name',function(Deposit $data){
                            $data = User::where('id',$data->user_id)->first();
                            return $data->name;
                        })
                        ->addColumn('customer_email',function(Deposit $data){
                            $data = User::where('id',$data->user_id)->first();
                            return $data->email;
                        })
                        ->editColumn('amount', function(Deposit $data) {
                            return showAdminAmount($data->amount);
                        })
                        ->editColumn('status', function(Deposit $data) {
                            if($data->status == 'pending'){
                                $status  =  __('pending');
                                $status_sign = 'warning';
                            }elseif($data->status == 'complete'){
                                $status  =  __('completed');
                                $status_sign = 'success';
                            }else{
                                $status  =  __('rejected');
                                $status_sign = 'danger';
                            }

                            return '<div class="btn-group mb-1">
                                    <button type="button" class="btn btn-'.$status_sign.' btn-sm btn-rounded dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    '.$status .'
                                    </button>
                                    <div class="dropdown-menu" x-placement="bottom-start">
                                        <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin.deposits.status',['id1' => $data->id, 'id2' => 'pending']).'">'.__("Pending").'</a>
                                        <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin.deposits.status',['id1' => $data->id, 'id2' => 'reject']).'">'.__("Reject").'</a>
                                        <a href="javascript:;" data-toggle="modal" data-target="#statusModal" class="dropdown-item" data-href="'. route('admin.deposits.status',['id1' => $data->id, 'id2' => 'complete']).'">'.__("Completed").'</a>
                                    </div>
                                </div>';
                        })
                        ->addColumn('action', function(Deposit $data) {
                            return '<div class="btn-group mb-1">
                                        <button type="button" class="btn btn-primary btn-sm btn-rounded dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        '.'Actions' .'
                                        </button>
                                        <div class="dropdown-menu" x-placement="bottom-start">
                                            <a href="javascript:;" data-href="' . route('admin.deposit.show',$data->id) . '"  class="dropdown-item" id="applicationDetails" data-toggle="modal" data-target="#details">'.__("Details").'</a>
                                        </div>
                                    </div>';
                         })
                        ->rawColumns(['created_at','customer_name','customer_email','amount','status','action'])
                        ->toJson();
    }

    public function index(){
        return view('admin.deposit.index');
    }

    public function depositdetails($id)
    {
        $deposit = Deposit::findOrFail($id);
        return view('admin.deposit.details',compact('deposit'));
    }

    public function status($id1,$id2){
        $data = Deposit::findOrFail($id1);
        $user = User::findOrFail($data->user_id);

        if($data->status == 'complete'){
          $msg = 'Deposit already completed-A';
          return response()->json($msg);
        }

        if($data->status == 'reject'){
            $msg = 'Deposit already rejected';
            return response()->json($msg);
        }

        if($id2 == 'pending'){
            $msg = 'Deposit updated successfully';
            return response()->json($msg);
        }

        if($id2 == 'reject'){
            $data->update(['status' => $id2]);

            $trans = new Transaction();
            $trans->email = $user->email;
            $trans->amount = $data->amount;
            $trans->type = "Deposit Reject";
            $trans->profit = "minus";
            $trans->txnid = $data->deposit_number;
            $trans->user_id = $user->id;
            $trans->save();

            $msg = 'Deposit rejected successfully';
            return response()->json($msg);
        }

        $data->update(['status' => $id2]);

        $user->balance += $data->amount;
        $user->save();

        $trans = new Transaction();
        $trans->email = $user->email;
        $trans->amount = $data->amount;
        $trans->type = "Deposit";
        $trans->profit = "plus";
        $trans->txnid = $data->deposit_number;
        $trans->user_id = $user->id;
        $trans->save();

        $data->update(['status' => $id2]);

        if($data->status == 'complete'){
            $gs = Generalsetting::findOrFail(1);
            $subject = 'Deposit Confirmed';
            $msg = '<!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1.0">
                        <title>Deposit Confirmed</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 are pleased to inform you that your deposit has been successfully received and credited to your account with <strong>Fluxe Assets</strong>.</p>
                    			<p>Your funds are now available and awaiting allocation to an investment PLAN of your choice.</p>
                    			<p>To proceed, please log in to your account to select a suitable PLAN. If you need assistance, feel free to <a href="https://fluxeassets.com/contact" style="color: #0073e6; text-decoration: none;" target="_blank">contact us</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' => "Deposit",
                    'cname' => $user->name,
                    'oamount' => $data->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
            {
                $to = $user->email;
                $subject = " You have deposited successfully.";
                $msg = "Hello ".$user->name."!\nYou have invested successfully.\nThank you.";
                $headers = "From: ".$gs->from_name."<".$gs->from_email.">";
                mail($to,$subject,$msg,$headers);
            }
        }

        $msg = 'Data Updated Successfully.';
        return response()->json($msg);
    }
}
