<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\PlanPurchase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PlanApiController extends Controller
{
    /**
     * Get all mining plans
     */
    public function index(Request $request)
    {
        try {
            $query = Plan::query();

            // Search functionality
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where('name', 'LIKE', "%{$search}%");
            }

            // Status filter
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            $perPage = $request->per_page ?? 15;
            $plans = $query->withCount(['purchases'])
                          ->orderBy('created_at', 'desc')
                          ->paginate($perPage);

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

    /**
     * Get specific plan details
     */
    public function show($id)
    {
        try {
            $plan = Plan::with(['purchases.user'])
                       ->withCount(['purchases'])
                       ->findOrFail($id);

            return response()->json([
                'status' => 'success',
                'data' => $plan
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Plan not found',
                'error' => $e->getMessage()
            ], 404);
        }
    }

    /**
     * Create new plan
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'description' => 'nullable|string',
                'price' => 'required|numeric|min:0',
                'min_amount' => 'required|numeric|min:0',
                'max_amount' => 'required|numeric|min:0|gte:min_amount',
                'daily_interest' => 'required|numeric|min:0|max:100',
                'duration' => 'required|integer|min:1',
                'capital_return' => 'required|boolean',
                'featured' => 'boolean',
                'status' => 'required|in:0,1',
                'image' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $plan = Plan::create($validator->validated());

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

    /**
     * Update plan
     */
    public function update(Request $request, $id)
    {
        try {
            $plan = Plan::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'description' => 'nullable|string',
                'price' => 'required|numeric|min:0',
                'min_amount' => 'required|numeric|min:0',
                'max_amount' => 'required|numeric|min:0|gte:min_amount',
                'daily_interest' => 'required|numeric|min:0|max:100',
                'duration' => 'required|integer|min:1',
                'capital_return' => 'required|boolean',
                'featured' => 'boolean',
                'status' => 'required|in:0,1',
                'image' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $plan->update($validator->validated());

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

    /**
     * Update plan status
     */
    public function updateStatus(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'status' => 'required|in:0,1'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $plan = Plan::findOrFail($id);
            $plan->update(['status' => $request->status]);

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

    /**
     * Delete plan
     */
    public function destroy($id)
    {
        try {
            $plan = Plan::findOrFail($id);
            
            // Check if plan has active purchases
            $activePurchases = PlanPurchase::where('plan_id', $id)
                                          ->where('status', 'active')
                                          ->count();
            
            if ($activePurchases > 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot delete plan with active purchases'
                ], 400);
            }

            $plan->delete();

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

    /**
     * Get plan purchases/orders
     */
    public function orders(Request $request)
    {
        try {
            $query = PlanPurchase::with(['user', 'plan']);

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

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

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

            // Date filter
            if ($request->has('date_from')) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }
            if ($request->has('date_to')) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }

            $perPage = $request->per_page ?? 15;
            $orders = $query->orderBy('created_at', 'desc')->paginate($perPage);

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