<?php

namespace App\Http\Controllers;

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

class CompanyController extends Controller
{
    protected $apiService;

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

    /**
     * Display a listing of companies.
     */
    public function index(Request $request)
    {
        try {
            // Obtener parámetros de filtrado
            $search = $request->get('search');
            $status = $request->get('status');
            $plan = $request->get('plan');
            $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;
            }

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

            // Llamar a la API usando la función estructural
            $response = $this->apiService->makeApiRequest('GET', config('api.companies.list'), [], $params, 'get_companies_index');
            
            if ($response && isset($response['success']) && $response['success']) {
                $responseData = $response['data'] ?? [];
                $apiData = $responseData['data'] ?? [];
                $companies = $apiData['businesses'] ?? [];
                $pagination = $apiData['pagination'] ?? [];
                $stats = $apiData['statistics'] ?? [];
            } else {
                $companies = [];
                $pagination = [];
                $stats = [];
                
                if (isset($response['message'])) {
                    session()->flash('error', 'Error al obtener empresas: ' . $response['message']);
                }
            }

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

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

        // Datos de ejemplo para desarrollo
        if (empty($companies)) {
            $companies = [
                [
                    'id' => 1,
                    'name' => 'Empresa Demo 1',
                    'email' => 'contacto@empresademo1.com',
                    'phone' => '+54 11 1234-5678',
                    'status' => 'active',
                    'current_plan' => 'PRO',
                    'plan_expires_at' => '2025-03-15',
                    'created_at' => '2024-01-15',
                ],
                [
                    'id' => 2,
                    'name' => 'Empresa Demo 2',
                    'email' => 'info@empresademo2.com',
                    'phone' => '+54 11 9876-5432',
                    'status' => 'active',
                    'current_plan' => 'LITE',
                    'plan_expires_at' => '2025-02-20',
                    'created_at' => '2024-02-10',
                ],
                [
                    'id' => 3,
                    'name' => 'Empresa Demo 3',
                    'email' => 'contacto@empresademo3.com',
                    'phone' => '+54 11 5555-5555',
                    'status' => 'suspended',
                    'current_plan' => 'PRO',
                    'plan_expires_at' => '2024-12-31',
                    'created_at' => '2023-12-01',
                ],
            ];

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

            $stats = [
                'total' => 3,
                'active' => 2,
                'with_plans' => 3,
                'recent' => 1,
            ];
        }

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

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

    /**
     * Store a newly created company in storage.
     */
    public function store(Request $request)
    {
        // Convertir los inputs en arrays con key-value
        $data = $request->all();
        
        // Separar los datos por prefijo
        $userData = [];
        $businessData = [];
        
        foreach ($data as $key => $value) {
            if (str_starts_with($key, 'user_')) {
                // Remover el prefijo 'user_' y agregar al array user
                $newKey = substr($key, 5); // Quita 'user_' (5 caracteres)
                $userData[$newKey] = $value;
            } elseif (str_starts_with($key, 'business_')) {
                // Remover el prefijo 'business_' y agregar al array business
                $newKey = substr($key, 9); // Quita 'business_' (9 caracteres)
                $businessData[$newKey] = $value;
            }
        }
        
        // Crear el array final con las dos secciones
        $processedData = [
            'user' => $userData,
            'business' => $businessData
        ];

        try {
            $response = $this->apiService->makeApiRequest(
                'POST',
                config('api.companies.create'),
                $processedData,
                [],
                'create_company'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('companies.index')
                    ->with('success', 'Empresa creada exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error desconocido';
                return back()->withErrors(['error' => $message])->withInput();
            }

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

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

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

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

            // Datos de ejemplo para desarrollo
            $company = [
                'id' => $id,
                'name' => 'Empresa Demo ' . $id,
                'email' => 'contacto@empresademo' . $id . '.com',
                'phone' => '+54 11 1234-567' . $id,
                'address' => 'Dirección de ejemplo ' . $id,
                'tax_id' => '20-12345678-' . $id,
                'status' => 'active',
                'current_plan' => 'PRO',
                'plan_expires_at' => '2025-03-15',
                'created_at' => '2024-01-15',
            ];
        }

        return view('companies.show', compact('company'));
    }

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

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

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

        return view('companies.edit', compact('company'));
    }

    /**
     * Update the specified company in storage.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:50',
            'address' => 'nullable|string|max:500',
            'tax_id' => 'nullable|string|max:100',
        ]);

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

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

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

    /**
     * Remove the specified company from storage.
     */
    public function destroy($id)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return back()->with('error', 'No tienes permisos para realizar esta acción.');
        }
        
        try {
            $response = $this->apiService->makeApiRequest(
                'DELETE',
                "/companies/{$id}",
                [],
                [],
                'delete_company'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('companies.index')
                    ->with('success', 'Empresa eliminada exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error al eliminar empresa';
                return back()->with('error', $message);
            }

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

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

    /**
     * Regenerate welcome token for a company.
     */
    public function regenerateWelcomeToken($id)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return response()->json([
                'success' => false,
                'message' => 'No tienes permisos para realizar esta acción.'
            ], 403);
        }
        
        try {
            // Usar la función estructural directamente
            $response = $this->apiService->makeApiRequest(
                'POST', 
                api_url('access_requests.regenerate_first_token'), 
                [
                    'businessId' => $id,
                    'sendWelcomeEmail' => true
                ], 
                [], 
                'regenerate_welcome_token'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                $responseData = $response['data'] ?? [];
                $welcomeUrl = $responseData['data']['first_login']['url'] ?? '';
                $token = $responseData['data']['first_login']['token'] ?? '';
                
                return response()->json([
                    'success' => true,
                    'message' => 'Token de bienvenida regenerado exitosamente.',
                    'data' => [
                        'welcome_url' => $welcomeUrl,
                        'token' => $token
                    ]
                ]);
            } else {
                $message = $response['message'] ?? 'Error al regenerar token';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('Error regenerating welcome token', [
                'company_id' => $id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error al conectar con el servidor.'
            ], 500);
        }
    }

    /**
     * Assign a plan to a company.
     */
    public function assignPlan(Request $request, $id)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return response()->json([
                'success' => false,
                'message' => 'No tienes permisos para realizar esta acción.'
            ], 403);
        }

        try {
            $response = $this->apiService->makeApiRequest(
                'POST',
                "/companies/{$id}/assign-plan",
                [
                    'plan_id' => $request->get('plan_id')
                ],
                [],
                'assign_plan_to_company'
            );

            if ($response && isset($response['success']) && $response['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Plan asignado exitosamente.'
                ]);
            } else {
                $message = $response['message'] ?? 'Error al asignar plan';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

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

            return response()->json([
                'success' => false,
                'message' => 'Error al conectar con el servidor.'
            ], 500);
        }
    }

    /**
     * Change company status.
     */
    public function changeStatus(Request $request, $id)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return response()->json([
                'success' => false,
                'message' => 'No tienes permisos para realizar esta acción.'
            ], 403);
        }

        try {
            $response = $this->apiService->makeApiRequest(
                'PUT',
                "/companies/{$id}/status",
                [
                    'status' => $request->get('status')
                ],
                [],
                'change_company_status'
            );

            if ($response && isset($response['success']) && $response['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Estado de la empresa actualizado exitosamente.'
                ]);
            } else {
                $message = $response['message'] ?? 'Error al cambiar estado';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('Error changing company status', [
                'company_id' => $id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error al conectar con el servidor.'
            ], 500);
        }
    }

    /**
     * Suspend a company.
     */
    public function suspend($id)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return response()->json([
                'success' => false,
                'message' => 'No tienes permisos para realizar esta acción.'
            ], 403);
        }

        try {
            $response = $this->apiService->makeApiRequest(
                'POST',
                "/companies/{$id}/suspend",
                [],
                [],
                'suspend_company'
            );

            if ($response && isset($response['success']) && $response['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Empresa suspendida exitosamente.'
                ]);
            } else {
                $message = $response['message'] ?? 'Error al suspender empresa';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

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

            return response()->json([
                'success' => false,
                'message' => 'Error al conectar con el servidor.'
            ], 500);
        }
    }

    /**
     * Send notification to a company.
     */
    public function sendNotification(Request $request, $id)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return response()->json([
                'success' => false,
                'message' => 'No tienes permisos para realizar esta acción.'
            ], 403);
        }

        try {
            $response = $this->apiService->makeApiRequest(
                'POST',
                "/companies/{$id}/notification",
                [
                    'message' => $request->get('message'),
                    'type' => $request->get('type', 'info')
                ],
                [],
                'send_company_notification'
            );

            if ($response && isset($response['success']) && $response['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Notificación enviada exitosamente.'
                ]);
            } else {
                $message = $response['message'] ?? 'Error al enviar notificación';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('Error sending notification to company', [
                'company_id' => $id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error al conectar con el servidor.'
            ], 500);
        }
    }

    /**
     * Export companies data.
     */
    public function export(Request $request)
    {
        // Verificar permisos de administrador
        $userType = session('backoffice_user_type');
        if ($userType !== 'admin') {
            return back()->with('error', 'No tienes permisos para realizar esta acción.');
        }

        try {
            $response = $this->apiService->makeApiRequest(
                'GET',
                '/companies/export',
                [],
                $request->query(),
                'export_companies'
            );

            if ($response && isset($response['data'])) {
                // En desarrollo, simulamos la descarga
                return response()->json([
                    'success' => true,
                    'message' => 'Exportación generada exitosamente.',
                    'download_url' => '/temp/companies_export.xlsx'
                ]);
            } else {
                $message = $response['message'] ?? 'Error al exportar datos';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

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

            return response()->json([
                'success' => false,
                'message' => 'Error al conectar con el servidor.'
            ], 500);
        }
    }
}