<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\User\OrderPlanController;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Miner;
use App\Models\Order;

class OrderPlanApiController extends Controller
{
    protected $orderPlanController;

    public function __construct()
    {
        $this->orderPlanController = new OrderPlanController();
    }

    /**
     * Get mining plans
     * @return JsonResponse
     */
    public function plans(): JsonResponse
    {
        try {
            $miners = Miner::with('activePlans')->whereHas('activePlans')->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'miners' => $miners
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch mining plans',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Order a mining plan
     * @param Request $request
     * @return JsonResponse
     */
    public function orderPlan(Request $request): JsonResponse
    {
        try {
            $result = $this->orderPlanController->orderPlan($request);
            
            if ($result instanceof \Illuminate\Http\RedirectResponse) {
                // If it's a redirect, check for success/error messages
                $session = $result->getSession();
                if ($session && $session->has('notify')) {
                    $notify = $session->get('notify');
                    $firstNotify = $notify[0] ?? null;
                    
                    if ($firstNotify && $firstNotify[0] === 'success') {
                        return response()->json([
                            'status' => 'success',
                            'message' => $firstNotify[1],
                            'redirect_url' => route('user.plans.purchased')
                        ]);
                    } else if ($firstNotify && $firstNotify[0] === 'error') {
                        return response()->json([
                            'status' => 'error',
                            'message' => $firstNotify[1]
                        ], 422);
                    }
                }
                
                return response()->json([
                    'status' => 'success',
                    'message' => 'Plan order processed successfully'
                ]);
            }

            return response()->json([
                'status' => 'success',
                'message' => 'Plan ordered successfully',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to order plan',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's mining tracks (purchased plans)
     * @return JsonResponse
     */
    public function miningTracks(): JsonResponse
    {
        try {
            $user = auth()->user();
            
            $orders = Order::where('user_id', $user->id)
                ->with('miner')
                ->orderBy('id', 'desc')
                ->paginate(20);

            return response()->json([
                'status' => 'success',
                'data' => [
                    'orders' => $orders
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch mining tracks',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get single order details
     * @param int $id
     * @return JsonResponse
     */
    public function show($id): JsonResponse
    {
        try {
            $user = auth()->user();
            
            $order = Order::where('user_id', $user->id)
                ->with('miner')
                ->findOrFail($id);

            return response()->json([
                'status' => 'success',
                'data' => [
                    'order' => $order
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch order details',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
