<?php

namespace App\Http\Controllers;

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

class CommercialAdvisorController extends Controller
{
    protected $apiService;

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

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

            // Llamar a la API usando la función estructural
            $response = $this->apiService->makeApiRequest('GET', api_url('commercial_advisors.list'), [], $params, 'get_advisors_index');
            
            $apiWorking = false;
            $advisors = [];
            $pagination = [];
            $stats = [];
            
            if ($response && isset($response['success']) && $response['success']) {
                $apiWorking = true;
                // El ApiService wrappea la respuesta, así que necesitamos acceder a data.data.data
                $apiResponseData = $response['data'] ?? [];  // Respuesta original de la API
                $responseData = $apiResponseData['data'] ?? [];  // Datos de paginación de la API
                
                // Validar que tengamos la estructura correcta de paginación
                if (!is_array($responseData) || !isset($responseData['data'])) {                    
                    $advisors = [];
                    $pagination = [
                        'current_page' => 1,
                        'total_pages' => 1,
                        'total_items' => 0,
                        'per_page' => 25,
                    ];
                    $stats = [
                        'total' => 0,
                        'active' => 0,
                        'inactive' => 0,
                        'total_sales' => 0,
                        'avg_commission' => 0,
                        'total_clients' => 0,
                    ];
                } else {
                    // Obtener los asesores del array data.data.data
                    $advisors = $responseData['data'] ?? [];
                    
                    // Asegurar que los advisors sean arrays
                    if (!empty($advisors)) {
                        $advisors = array_map(function($advisor) {
                            return is_object($advisor) ? (array) $advisor : $advisor;
                        }, $advisors);
                    }
                    
                    // Construir paginación desde la respuesta de la API
                    $pagination = [
                        'current_page' => $responseData['current_page'] ?? 1,
                        'total_pages' => $responseData['last_page'] ?? 1,
                        'total_items' => $responseData['total'] ?? 0,
                        'per_page' => $responseData['per_page'] ?? 25,
                    ];
                    
                    // Construir estadísticas básicas
                    $stats = [
                        'total' => $responseData['total'] ?? 0,
                        'active' => 0,
                        'inactive' => 0,
                        'total_sales' => 0,
                        'avg_commission' => 0,
                        'total_clients' => 0,
                    ];
                    
                    // Calcular estadísticas si hay datos
                    if (!empty($advisors)) {
                        foreach ($advisors as $advisor) {
                            if (($advisor['status'] ?? '') === 'active') {
                                $stats['active']++;
                            } else {
                                $stats['inactive']++;
                            }
                            
                            $stats['total_sales'] += $advisor['total_sales'] ?? 0;
                            $stats['total_clients'] += $advisor['clients_count'] ?? 0;
                        }
                        
                        $stats['avg_commission'] = count($advisors) > 0 
                            ? array_sum(array_column($advisors, 'commission_rate')) / count($advisors)
                            : 0;
                    }
                }
            } else {
                // API no funciona, mostrar arrays vacíos
                $advisors = [];
                $pagination = [
                    'current_page' => 1,
                    'total_pages' => 1,
                    'total_items' => 0,
                    'per_page' => 25,
                ];
                $stats = [
                    'total' => 0,
                    'active' => 0,
                    'inactive' => 0,
                    'total_sales' => 0,
                    'avg_commission' => 0,
                    'total_clients' => 0,
                ];
                
                if (isset($response['message'])) {
                    session()->flash('error', 'Error al obtener asesores comerciales: ' . $response['message']);
                }
            }

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

            $apiWorking = false;
            $advisors = [];
            $pagination = [
                'current_page' => 1,
                'total_pages' => 1,
                'total_items' => 0,
                'per_page' => 25,
            ];
            $stats = [
                'total' => 0,
                'active' => 0,
                'inactive' => 0,
                'total_sales' => 0,
                'avg_commission' => 0,
                'total_clients' => 0,
            ];
            session()->flash('error', 'Error al conectar con el servidor.');
        }

        return view('commercial-advisors.index', compact('advisors', 'pagination', 'stats', 'search', 'status', 'region', 'apiWorking'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // Obtener las regiones disponibles (esto podría venir de una API o configuración)
        $regions = [
            'Capital Federal',
            'Zona Norte',
            'Zona Sur',
            'Zona Oeste',
            'Interior - Buenos Aires',
            'Córdoba',
            'Santa Fe',
            'Mendoza',
            'Otros'
        ];

        return view('commercial-advisors.create', compact('regions'));
    }

    /**
     * Store a newly created commercial advisor in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:50',
            'region' => 'required|string|max:255',
            'commission_rate' => 'required|numeric|min:0|max:100',
            'passive_commission_rate' => 'nullable|numeric|min:0|max:100',
            'payment_period' => 'nullable|string|in:daily,weekly,biweekly,monthly',
            'address' => 'nullable|string|max:500',
            'dni' => 'nullable|string|max:20',
            'notes' => 'nullable|string|max:1000',
            'username' => 'required|string|min:3|max:50|regex:/^[a-zA-Z0-9._-]+$/',
            'password' => 'required|string|min:8|confirmed',
            'send_credentials' => 'nullable|boolean',
        ]);

        try {
            $response = $this->apiService->makeApiRequest(
                'POST',
                api_url('commercial_advisors.create'),
                $request->all(),
                [],
                'create_advisor'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                // Si es una request AJAX (para mostrar el modal), retornar JSON
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'success' => true,
                        'message' => 'Asesor comercial creado exitosamente.',
                        'advisor' => [
                            'name' => $request->name,
                            'lastName' => $request->last_name,
                            'email' => $request->email,
                            'phone' => $request->phone,
                            'username' => $request->username,
                            'password' => $request->password
                        ]
                    ]);
                }
                
                // Redirección normal con datos en sesión para mostrar el modal
                return redirect()->route('commercial-advisors.create')
                    ->with('success', 'Asesor comercial creado exitosamente.')
                    ->with('show_credentials_modal', true)
                    ->with('advisor_data', [
                        'name' => $request->name,
                        'lastName' => $request->last_name,
                        'email' => $request->email,
                        'phone' => $request->phone,
                        'username' => $request->username,
                        'password' => $request->password
                    ]);
            } else {
                $message = $response['message'] ?? 'Error desconocido';
                
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $message
                    ], 400);
                }
                
                return back()->withErrors(['error' => $message])->withInput();
            }

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

            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error al conectar con el servidor.'
                ], 500);
            }

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

    /**
     * Display the specified commercial advisor.
     */
    public function show($id)
    {
        try {
            $response = $this->apiService->makeApiRequest(
                'GET',
                api_url('commercial_advisors.show', ['id' => $id]),
                [],
                [],
                'get_advisor_detail'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                $advisor = $response['data'] ?? null;
                
                // Si la API responde exitosamente pero no hay datos, el asesor no existe
                if (!$advisor) {
                    return redirect()->route('commercial-advisors.index')
                        ->with('error', 'Asesor comercial no encontrado.');
                }
            } else {
                // Error en la API, redirigir con mensaje de error
                $message = $response['message'] ?? 'Error al obtener datos del asesor comercial';
                
                return redirect()->route('commercial-advisors.index')->with('error', $message);
            }

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

            return redirect()->route('commercial-advisors.index')
                ->with('error', 'Error al conectar con el servidor.');
        }

        return view('commercial-advisors.show', compact('advisor'));
    }

    /**
     * Show the form for editing the specified commercial advisor.
     */
    public function edit($id)
    {
        try {
            $response = $this->apiService->makeApiRequest(
                'GET',
                api_url('commercial_advisors.show', ['id' => $id]),
                [],
                [],
                'get_advisor_for_edit'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                $advisor = $response['data'] ?? null;
                
                // Si la API responde exitosamente pero no hay datos, el asesor no existe
                if (!$advisor) {
                    return redirect()->route('commercial-advisors.index')
                        ->with('error', 'Asesor comercial no encontrado.');
                }
            } else {
                $message = $response['message'] ?? 'Error al obtener datos del asesor comercial';
                return redirect()->route('commercial-advisors.index')->with('error', $message);
            }

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

            return redirect()->route('commercial-advisors.index')
                ->with('error', 'Error al conectar con el servidor.');
        }

        // Obtener las regiones disponibles
        $regions = [
            'Capital Federal',
            'Zona Norte',
            'Zona Sur',
            'Zona Oeste',
            'Interior - Buenos Aires',
            'Córdoba',
            'Santa Fe',
            'Mendoza',
            'Otros'
        ];

        return view('commercial-advisors.edit', compact('advisor', 'regions'));
    }

    /**
     * Update the specified commercial advisor in storage.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:50',
            'region' => 'required|string|max:255',
            'commission_rate' => 'required|numeric|min:0|max:100',
            'address' => 'nullable|string|max:500',
            'dni' => 'nullable|string|max:20',
            'notes' => 'nullable|string|max:1000',
            'status' => 'required|in:active,inactive',
        ]);

        try {
            $response = $this->apiService->makeApiRequest(
                'PUT',
                api_url('commercial_advisors.update', ['id' => $id]),
                $request->all(),
                [],
                'update_advisor'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('commercial-advisors.show', $id)
                    ->with('success', 'Asesor comercial actualizado exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error desconocido';
                return back()->withErrors(['error' => $message])->withInput();
            }

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

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

    /**
     * Remove the specified commercial advisor from storage.
     */
    public function destroy($id)
    {
        try {
            $response = $this->apiService->makeApiRequest(
                'DELETE',
                api_url('commercial_advisors.delete', ['id' => $id]),
                [],
                [],
                'delete_advisor'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                return redirect()->route('commercial-advisors.index')
                    ->with('success', 'Asesor comercial eliminado exitosamente.');
            } else {
                $message = $response['message'] ?? 'Error al eliminar asesor comercial';
                return back()->with('error', $message);
            }

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

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

    /**
     * Update the status of a commercial advisor.
     */
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:active,inactive',
        ]);

        try {
            $response = $this->apiService->makeApiRequest(
                'PATCH',
                api_url('commercial_advisors.change_status', ['id' => $id]),
                ['status' => $request->status],
                [],
                'change_advisor_status'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Estado actualizado exitosamente.',
                ]);
            } else {
                $message = $response['message'] ?? 'Error al actualizar estado';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

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

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

    /**
     * Export commercial advisors data.
     */
    public function export(Request $request)
    {
        try {
            $params = [
                'format' => 'excel',
                'search' => $request->get('search'),
                'status' => $request->get('status'),
                'region' => $request->get('region'),
            ];

            $response = $this->apiService->makeApiRequest(
                'GET',
                api_url('commercial_advisors.export'),
                [],
                $params,
                'export_advisors'
            );
            
            if ($response && isset($response['success']) && $response['success']) {
                // En producción, esto descargaría el archivo
                return response()->json([
                    'success' => true,
                    'message' => 'Exportación iniciada. Recibirás un email cuando esté lista.',
                ]);
            } else {
                $message = $response['message'] ?? 'Error en la exportación';
                return response()->json([
                    'success' => false,
                    'message' => $message
                ], 400);
            }

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

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