<?php

namespace App\Http\Controllers;

use App\Models\Investment;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;
use Tymon\JWTAuth\Claims\Custom;
use App\Models\Customer;
use App\Models\CustomerInvestment;
use Illuminate\Support\Facades\DB;
use App\Notifications\InvestmentJoinedNotification;

class InvestmentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        $query = Investment::query();

        // Filter by status if provided
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        // Filter by active/inactive
        if ($request->has('active')) {
            $query->where('status', $request->boolean('active') ? 'active' : 'inactive');
        }

        // Include soft deleted if requested
        if ($request->boolean('include_deleted')) {
            $query->withTrashed();
        }

        $investments = $query->orderBy('created_at', 'desc')->get();

        return response()->json([
            'success' => true,
            'data' => $investments,
            'message' => 'Investments retrieved successfully'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'min_amount' => 'required|numeric|min:0',
            'max_amount' => 'required|numeric|min:0|gt:min_amount',
            'investment_name' => 'required|string|max:255|unique:investments,investment_name',
            'investment_description' => 'nullable|string|max:1000',
            'bonus' => 'nullable|numeric|min:0',
            'percentage' => 'required|numeric|min:0',
            'duration' => 'required|integer|min:1',
            'status' => ['nullable', Rule::in(['active', 'inactive', 'pending', 'completed'])],
        ]);

        try {
            $investment = Investment::create($validated);

            return response()->json([
                'success' => true,
                'data' => $investment,
                'message' => 'Investment created successfully'
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create investment: ' . $e->getMessage()
            ], 500);
        }
    }

    public function customerInvestmentList(Request $request)
    {
        $query = \App\Models\CustomerInvestment::where("customer_id", auth("customer")->user()->id);

        // Optional: Filter by status if provided
        if ($request->has('status')) {
            $query->where('status', $request->input('status'));
        }

        // Paginate results (default 10 per page)
        $perPage = $request->input('per_page', 10);
        $customerInvestments = $query->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => $customerInvestments,
            'pagination' => [
                'current_page' => $customerInvestments->currentPage(),
                'last_page' => $customerInvestments->lastPage(),
                'per_page' => $customerInvestments->perPage(),
                'total' => $customerInvestments->total(),
                'from' => $customerInvestments->firstItem(),
                'to' => $customerInvestments->lastItem(),
            ],
            'message' => 'Customer investments retrieved successfully'
        ]);
    }

    public function joinInvestment(Request $request)
    {
        return DB::transaction(function () use ($request) {
            try {
                $customer = auth('customer')->user();
                $customer = Customer::find($customer->id);
                $request->validate([
                    'customer_id' => 'required|exists:customers,id',
                    'investment_id' => 'required|exists:investments,id',
                    'amount' => 'required|numeric|min:0',
                ]);
                $investment = Investment::find($request->investment_id);
                if (!$investment) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Investment not found'
                    ], 400);
                }

                if (!$investment->isAmountInRange($request->amount)) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Amount is outside the allowed range'
                    ], 400);
                }

                if ($customer->balance < $request->amount) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Insufficient balance to join this investment'
                    ], 400);
                }
                $now = now()->timestamp;
                $end = now()->addDays($investment->duration)->timestamp;

                $customerInvestment = \App\Models\CustomerInvestment::create([
                    'customer_id' => $request->customer_id,
                    'investment_id' => $request->investment_id,
                    'amount' => $request->amount,
                    'start_seconds' => $now,
                    'end_seconds' => $end,
                    'status' => 'active',
                ]);
                $customer->withdraw($request->amount, [
                    'type' => 'investment',
                    'reference_id' => $customerInvestment->id,
                    'description' => 'Joined investment: ' . $investment->investment_name
                ]);

                // Send notification to customer
                $customer->notify(new InvestmentJoinedNotification($customerInvestment));

                return response()->json([
                    'success' => true,
                    'data' => $customerInvestment,
                    'message' => 'Customer joined investment successfully'
                ], 201);
            } catch (\Exception $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to join investment: ' . $e->getMessage()
                ], 500);
            }
        });
    }

    /**
     * Display the specified resource.
     */
    public function show(Investment $investment): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $investment,
            'message' => 'Investment retrieved successfully'
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function showCustomerInvestment(CustomerInvestment $customerInvestment): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $customerInvestment,
            'message' => 'Investment retrieved successfully'
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Investment $investment): JsonResponse
    {
        $validated = $request->validate([
            'min_amount' => 'sometimes|numeric|min:0',
            'max_amount' => 'sometimes|numeric|min:0|gt:min_amount',
            'investment_name' => [
                'sometimes',
                'string',
                'max:255',
                Rule::unique('investments')->ignore($investment->id)
            ],
            'investment_description' => 'sometimes|nullable|string|max:1000',
            'bonus' => 'sometimes|nullable|numeric|min:0',
            'duration' => 'sometimes|integer|min:1',
            'status' => ['sometimes', Rule::in(['active', 'inactive', 'pending', 'completed'])],
        ]);

        try {
            $investment->update($validated);

            return response()->json([
                'success' => true,
                'data' => $investment->fresh(),
                'message' => 'Investment updated successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update investment: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage (soft delete).
     */
    public function destroy(Investment $investment): JsonResponse
    {
        try {
            $investment->delete();

            return response()->json([
                'success' => true,
                'message' => 'Investment deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete investment: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Restore a soft deleted investment.
     */
    public function restore($id): JsonResponse
    {
        try {
            $investment = Investment::withTrashed()->findOrFail($id);
            $investment->restore();

            return response()->json([
                'success' => true,
                'data' => $investment,
                'message' => 'Investment restored successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to restore investment: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Permanently delete an investment.
     */
    public function forceDelete($id): JsonResponse
    {
        try {
            $investment = Investment::withTrashed()->findOrFail($id);
            $investment->forceDelete();

            return response()->json([
                'success' => true,
                'message' => 'Investment permanently deleted'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to permanently delete investment: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get active investments only.
     */
    public function active(): JsonResponse
    {
        $investments = Investment::active()->get();

        return response()->json([
            'success' => true,
            'data' => $investments,
            'message' => 'Active investments retrieved successfully'
        ]);
    }

    /**
     * Toggle investment status between active and inactive.
     */
    public function toggleStatus(Investment $investment): JsonResponse
    {
        try {
            $newStatus = $investment->status === 'active' ? 'inactive' : 'active';
            $investment->update(['status' => $newStatus]);

            return response()->json([
                'success' => true,
                'data' => $investment,
                'message' => "Investment status changed to {$newStatus}"
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to toggle status: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Validate if an amount is within investment range.
     */
    public function validateAmount(Request $request, Investment $investment): JsonResponse
    {
        $request->validate([
            'amount' => 'required|numeric|min:0'
        ]);

        $amount = $request->amount;
        $isValid = $investment->isAmountInRange($amount);

        return response()->json([
            'success' => true,
            'data' => [
                'amount' => $amount,
                'is_valid' => $isValid,
                'min_amount' => $investment->min_amount,
                'max_amount' => $investment->max_amount,
                'investment_name' => $investment->investment_name
            ],
            'message' => $isValid ? 'Amount is within range' : 'Amount is outside the allowed range'
        ]);
    }
}
