<?php

namespace App\Http\Controllers;

use App\Models\Transfer;
use App\Models\Role;
use App\Models\User;
use App\Models\Funding;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Notifications\GeneralNotification;
use App\Services\AdminNotificationService;

class TransferController extends Controller
{
    /**
     * Create a new fund transfer request
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'recipient_email' => 'required|email',
            'amount' => 'required|numeric|min:0.01',
            'destination' => 'required',
            'description' => 'nullable|string'
        ]);

        $user = Auth::user();
        
        // Check if user has sufficient balance in Overall Assets
        $balance = $user->balance();
        if ($balance < $request->amount) {
            return response()->json([
                'status' => 'error',
                'message' => 'Insufficient balance in Overall Assets'
            ], 400);
        }

        // Find recipient by email
        $recipient = User::where('email', $request->recipient_email)->first();
        if (!$recipient) {
            return response()->json([
                'status' => 'error',
                'message' => 'Recipient not found'
            ], 404);
        }

        if ($recipient->id === $user->id) {
            return response()->json([
                'status' => 'error',
                'message' => 'You cannot transfer funds to yourself'
            ], 400);
        }

        // Generate unique reference
        $reference = 'TRF-' . time() . '-' . strtoupper(substr(md5(uniqid()), 0, 8));

        // Create transfer record (user_id is kept for backward compatibility)
        $transfer = new Transfer;
        $transfer->user_id = $user->id; // For backward compatibility with old structure
        $transfer->sender_id = $user->id;
        $transfer->recipient_id = $recipient->id;
        $transfer->amount = $request->amount;
        $transfer->destination = $request->destination;
        $transfer->description = $request->description ?? 'Fund transfer';
        $transfer->reference = $reference;
        $transfer->status = 'pending';
        $transfer->save();

        // Send admin notification
        AdminNotificationService::newTransferRequest($transfer);

        // Notify user
        $notification_details = [
            'title' => 'Transfer Request Submitted',
            'content' => 'Your transfer request of $' . number_format($request->amount, 2) . ' to ' . $recipient->email . ' has been submitted and is pending admin approval.',
            'mail_content' => "Dear " . $user->name . ", <br/><br/> Your transfer request of $" . number_format($request->amount, 2) . " to " . $recipient->email . " has been submitted successfully. It is pending admin approval.<br/><br/>Reference: " . $reference . "<br/><br/>Thank you.",
            'url' => '/transfer'
        ];
        $activity = (object)$notification_details;
        $user->notify(new GeneralNotification($activity));

        return response()->json([
            'status' => 'success',
            'message' => 'Transfer is processing. You will be notified when the transfer is completed.',
            'transfer' => $transfer->load(['sender', 'recipient'])
        ], 200);
    }

    /**
     * Get pending transfers for admin
     *
     * @return \Illuminate\Http\Response
     */
    public function getPendingTransfers()
    {
        $transfers = Transfer::where('status', 'pending')
            ->orderByDesc('created_at')
            ->with(['sender', 'recipient'])
            ->get();

        return response()->json([
            'status' => 'success',
            'transfers' => $transfers
        ], 200);
    }

    /**
     * Admin approve or reject transfer
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function adminApproveTransfer(Request $request, $id)
    {
        $request->validate([
            'action' => 'required|in:approved,rejected',
            'admin_notes' => 'nullable|string'
        ]);

        $transfer = Transfer::find($id);
        if (!$transfer) {
            return response()->json([
                'status' => 'error',
                'message' => 'Transfer not found'
            ], 404);
        }

        if ($transfer->status !== 'pending') {
            return response()->json([
                'status' => 'error',
                'message' => 'Transfer has already been processed'
            ], 400);
        }

        $sender = $transfer->sender;
        $recipient = $transfer->recipient;

        if ($request->action === 'approved') {
            // Check sender still has sufficient balance
            $senderBalance = $sender->balance();
            if ($senderBalance < $transfer->amount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Sender no longer has sufficient balance'
                ], 400);
            }

            // Generate transfer transaction ID
            $transferTransactionId = 'TRANSFER-' . $transfer->reference;

            // Debit from sender's Overall Asset (negative amount)
            $senderFunding = new Funding;
            $senderFunding->user_id = $sender->id;
            $senderFunding->amount = -$transfer->amount;
            $senderFunding->status = 'successful';
            $senderFunding->gateway = 'Overall Asset';
            $senderFunding->transaction_id = $transferTransactionId;
            $senderFunding->save();

            // Credit to recipient's Overall Asset (positive amount)
            $recipientFunding = new Funding;
            $recipientFunding->user_id = $recipient->id;
            $recipientFunding->amount = $transfer->amount;
            $recipientFunding->status = 'successful';
            $recipientFunding->gateway = 'Overall Asset';
            $recipientFunding->transaction_id = $transferTransactionId;
            $recipientFunding->save();

            $transfer->status = 'approved';
            $transfer->admin_notes = $request->admin_notes;
            $transfer->processed_at = now();
            $transfer->save();

            // Notify sender
            $senderNotification = [
                'title' => 'Transfer Approved',
                'content' => 'Your transfer of $' . number_format($transfer->amount, 2) . ' to ' . $recipient->email . ' has been approved.',
                'mail_content' => "Dear " . $sender->name . ", <br/><br/> Your transfer of $" . number_format($transfer->amount, 2) . " to " . $recipient->email . " has been approved and processed.<br/><br/>Reference: " . $transfer->reference . "<br/><br/>Thank you.",
                'url' => '/transfer'
            ];
            $senderActivity = (object)$senderNotification;
            $sender->notify(new GeneralNotification($senderActivity));

            // Notify recipient
            $recipientNotification = [
                'title' => 'Funds Received',
                'content' => 'You have received $' . number_format($transfer->amount, 2) . ' from ' . $sender->email . '.',
                'mail_content' => "Dear " . $recipient->name . ", <br/><br/> You have received $" . number_format($transfer->amount, 2) . " from " . $sender->email . ".<br/><br/>Reference: " . $transfer->reference . "<br/><br/>Thank you.",
                'url' => '/wallet'
            ];
            $recipientActivity = (object)$recipientNotification;
            $recipient->notify(new GeneralNotification($recipientActivity));

            return response()->json([
                'status' => 'success',
                'message' => 'Transfer approved and processed successfully',
                'transfer' => $transfer->load(['sender', 'recipient'])
            ], 200);
        } else {
            // Reject transfer
            $transfer->status = 'rejected';
            $transfer->admin_notes = $request->admin_notes;
            $transfer->processed_at = now();
            $transfer->save();

            // Notify sender
            $senderNotification = [
                'title' => 'Transfer Rejected',
                'content' => 'Your transfer of $' . number_format($transfer->amount, 2) . ' to ' . $recipient->email . ' has been rejected.',
                'mail_content' => "Dear " . $sender->name . ", <br/><br/> Your transfer of $" . number_format($transfer->amount, 2) . " to " . $recipient->email . " has been rejected.<br/><br/>Reference: " . $transfer->reference . "<br/><br/>Reason: " . ($request->admin_notes ?? 'No reason provided') . "<br/><br/>Thank you.",
                'url' => '/transfer'
            ];
            $senderActivity = (object)$senderNotification;
            $sender->notify(new GeneralNotification($senderActivity));

            return response()->json([
                'status' => 'success',
                'message' => 'Transfer rejected',
                'transfer' => $transfer->load(['sender', 'recipient'])
            ], 200);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function show(Transfer $transfer)
    {
        $transfers = $transfer->whereDate('created_at', date('Y-m-d', strtotime('today')))->orderByDesc('id')->get()->load(['user']);
        return response()->json([
            'status' => 'success',
            'message' => 'transfers loaded successfully',
            'transfers' => $transfers,
        ], 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function edit(Transfer $transfer)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Transfer $transfer)
    {
        $request->validate([
            'amount' => 'required',
            'gateway' => 'required',
            'transaction_id' => 'required',
            'transfer_id' => 'required'
        ]);

        $transfer = Transfer::find($request->transfer_id);
        if (!$transfer) {
            return response()->json([
                'status' => 'error',
                'message' => 'transfer not found'
            ], 400);
        }

        $user = $transfer->user;
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'user not found'
            ], 400);
        }

        

        $transfer->status = 'approved';
        $transfer->save();

        $funding = new Funding;
        $funding->user_id = $user->id;
        $funding->amount = $request->amount;
        $funding->status = 'successful';
        $funding->gateway = $request->gateway;
        $funding->transaction_id = $request->transaction_id;
        $funding->save();

        $account = $user->load(['fundings', 'subscriptions', 'referrals', 'roles', 'plates.user']);
        $funding_bal = $user->balance();
        $sub_bal = $user->subscriptionBalance();
        $ref_bal = $user->referralEarning();

        $title = 'Payment Approved';
        $message = 'Your payment of '.$request->amount. ' has been approved and credited to your account.';
        $image = $user->profile;
        $action = '/wallet';
        $user->pushMessage($title, $message, $image, $action);

         // notify the user of order status
         $notification_details = [
            'title' => 'Payment Approved',
            'content' => 'Your payment of  NGN'.number_format($request->amount, 2, '.', ','). ' has been approved ',            
            'mail_content' => "Dear ".$user->name .", <br/><br/> This is to notify you that your payment of NGN".number_format($request->amount, 2, '.', ',')." has been approved by admin and your wallet credited successfully, kindly check your balance now to confrim.<br/><br/>
            Thank you for choosing Menubar Kitchen.
            "
            ,
            'url' => '/wallet'
        ];
        $activity = (object)$notification_details;
        $user->notify(new GeneralNotification($activity));

        return response()->json([
            'status' => 'success',
            'message' => 'user funded successfully',
            'user' => $account,
            'funding_bal' => $funding_bal,
            'sub_bal' => $sub_bal,
            'ref_bal' => $ref_bal,
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Transfer $transfer)
    {
        //
    }
}
