<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\ApiService;
use Illuminate\Support\Facades\Log;

class PlanController extends Controller
{
    protected $apiService;

    public function __construct(ApiService $apiService)
    {
        $this->apiService = $apiService;
    }

    /**
     * Display a listing of plans.
     */
    public function index(Request $request)
    {
        try {
            // Obtener parámetros de filtrado
            $search = $request->get('search');
            $status = $request->get('status');
            $page = $request->get('page', 1);
            $perPage = $request->get('per_page', 25);

            // Parámetros para la API
            $params = [
                'page' => $page,
                'per_page' => $perPage,
            ];

            if ($search) {
                $params['search'] = $search;
            }

            if ($status) {
                $params['status'] = $status;
            }

            // Llamar a la API
            $response = $this->apiService->makeApiRequest('GET', '/plans', [], $params, 'list_plans');
            
            if ($response && isset($response['success']) && $response['success']) {
                $plans = $response['data']['data'] ?? [];
                $pagination = $response['data']['pagination'] ?? [];
                $stats = $response['data']['stats'] ?? [];
            } else {
                $plans = [];
                $pagination = [];
                $stats = [];
                
                if (isset($response['message'])) {
                    session()->flash('error', 'Error al obtener planes: ' . $response['message']);
                }
            }

        } catch (\Exception $e) {
            Log::error('Error fetching plans', [
                'error' => $e->getMessage(),
                'params' => $params ?? []
            ]);

            $plans = [];
            $pagination = [];
            $stats = [];
            session()->flash('error', 'Error al conectar con el servidor. Mostrando datos de ejemplo.');
        }

        // Datos de ejemplo para desarrollo
        if (empty($plans)) {
            $plans = [
                [
                    'id' => 1,
                    'name' => 'LITE',
                    'code' => 'LITE',
                    'description' => 'Plan básico con funcionalidades esenciales para pequeños negocios',
                    'price' => 2500.00,
                    'duration_months' => 1,
                    'features' => [
                        'Facturación básica',
                        'Gestión de productos',
                        'Gestión de clientes',
                        'Reportes básicos'
                    ],
                    'is_active' => true,
                    'is_popular' => false,
                    'created_at' => '2024-01-01',
                    'active_subscriptions' => 15,
                    'company_count' => 15,
                    'monthly_revenue' => 37500.00,
                ],
                [
                    'id' => 2,
                    'name' => 'PRO',
                    'code' => 'PRO',
                    'description' => 'Plan profesional con funcionalidades completas para empresas',
                    'price' => 4500.00,
                    'duration_months' => 1,
                    'features' => [
                        'Facturación completa',
                        'Integración AFIP',
                        'Reportes avanzados',
                        'Múltiples usuarios',
                        'Soporte prioritario'
                    ],
                    'is_active' => true,
                    'is_popular' => true,
                    'created_at' => '2024-01-01',
                    'active_subscriptions' => 8,
                    'company_count' => 8,
                    'monthly_revenue' => 36000.00,
                ],
                [
                    'id' => 3,
                    'name' => 'ENTERPRISE',
                    'code' => 'ENTERPRISE',
                    'description' => 'Plan empresarial con todas las funcionalidades y soporte dedicado',
                    'price' => 8500.00,
                    'duration_months' => 1,
                    'features' => [
                        'Todas las funcionalidades PRO',
                        'API personalizada',
                        'Integraciones avanzadas',
                        'Soporte 24/7',
                        'Consultor dedicado'
                    ],
                    'is_active' => false,
                    'is_popular' => false,
                    'created_at' => '2024-01-01',
                    'active_subscriptions' => 0,
                    'company_count' => 0,
                    'monthly_revenue' => 0.00,
                ],
            ];

            $pagination = [
                'current_page' => 1,
                'total_pages' => 1,
                'total_items' => 3,
                'per_page' => 25,
            ];

            $stats = [
                'active_plans' => 2,
                'companies_with_plans' => 23,
                'monthly_revenue' => 73500.00,
            ];
        }

        return view('plans.index', compact('plans', 'pagination', 'stats', 'search', 'status'));
    }

    /**
     * Show the form for creating a new plan.
     */
    public function create()
    {
        return view('plans.create');
    }

    /**
     * Store a newly created plan in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:plans,code',
            'description' => 'required|string|max:1000',
            'price' => 'required|numeric|min:0',
            'duration_months' => 'required|integer|min:1',
            'features' => 'required|array',
            'features.*' => 'string|max:255',
        ]);

        try {
            $response = $this->apiService->makeApiRequest('POST', '/plans', $request->all(), [], 'create_plan');
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('plans.index')
                    ->with('success', 'Plan creado exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error desconocido';
                return back()->withErrors(['error' => $message])->withInput();
            }

        } catch (\Exception $e) {
            Log::error('Error creating plan', [
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return back()->withErrors(['error' => 'Error al conectar con el servidor.'])->withInput();
        }
    }

    /**
     * Display the specified plan.
     */
    public function show($id)
    {
        try {
            $response = $this->apiService->makeApiRequest('GET', "/plans/{$id}", [], [], 'show_plan');
            
            if ($response && isset($response['success']) && $response['success']) {
                $plan = $response['data'] ?? null;
            } else {
                $plan = null;
                $message = $response['message'] ?? 'Plan no encontrado';
                return redirect()->route('plans.index')->with('error', $message);
            }

        } catch (\Exception $e) {
            Log::error('Error fetching plan', [
                'id' => $id,
                'error' => $e->getMessage()
            ]);

            // Datos de ejemplo para desarrollo
            $plan = [
                'id' => $id,
                'name' => 'Plan Demo ' . $id,
                'code' => 'DEMO_' . $id,
                'description' => 'Descripción del plan demo ' . $id,
                'price' => 2500.00 * $id,
                'duration_months' => 1,
                'features' => [
                    'Característica 1',
                    'Característica 2',
                    'Característica 3'
                ],
                'is_active' => true,
                'created_at' => '2024-01-01',
                'active_subscriptions' => 5,
            ];
        }

        return view('plans.show', compact('plan'));
    }

    /**
     * Show the form for editing the specified plan.
     */
    public function edit($id)
    {
        try {
            $response = $this->apiService->makeApiRequest('GET', "/plans/{$id}", [], [], 'edit_plan');
            
            if ($response && isset($response['success']) && $response['success']) {
                $plan = $response['data'] ?? null;
            } else {
                $plan = null;
                $message = $response['message'] ?? 'Plan no encontrado';
                return redirect()->route('plans.index')->with('error', $message);
            }

        } catch (\Exception $e) {
            Log::error('Error fetching plan for edit', [
                'id' => $id,
                'error' => $e->getMessage()
            ]);

            return redirect()->route('plans.index')->with('error', 'Error al cargar plan.');
        }

        return view('plans.edit', compact('plan'));
    }

    /**
     * Update the specified plan in storage.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50',
            'description' => 'required|string|max:1000',
            'price' => 'required|numeric|min:0',
            'duration_months' => 'required|integer|min:1',
            'features' => 'required|array',
            'features.*' => 'string|max:255',
        ]);

        try {
            $response = $this->apiService->makeApiRequest('PUT', "/plans/{$id}", $request->all(), [], 'update_plan');
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('plans.show', $id)
                    ->with('success', 'Plan actualizado exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error desconocido';
                return back()->withErrors(['error' => $message])->withInput();
            }

        } catch (\Exception $e) {
            Log::error('Error updating plan', [
                'id' => $id,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return back()->withErrors(['error' => 'Error al conectar con el servidor.'])->withInput();
        }
    }

    /**
     * Remove the specified plan from storage.
     */
    public function destroy($id)
    {
        try {
            $response = $this->apiService->makeApiRequest('DELETE', "/plans/{$id}", [], [], 'delete_plan');
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('plans.index')
                    ->with('success', 'Plan eliminado exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error al eliminar plan';
                return back()->with('error', $message);
            }

        } catch (\Exception $e) {
            Log::error('Error deleting plan', [
                'id' => $id,
                'error' => $e->getMessage()
            ]);

            return back()->with('error', 'Error al conectar con el servidor.');
        }
    }
}