<?php

namespace App\Http\Controllers;

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

class PaymentController extends Controller
{
    protected $apiService;

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

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

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

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

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

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

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

        // Si no hay datos de la API, usar datos de ejemplo
        if (empty($payments)) {
            $payments = [
                [
                    'id' => 1,
                    'company_name' => 'Empresa Demo 1',
                    'plan_name' => 'PRO',
                    'amount' => 4500.00,
                    'currency' => 'ARS',
                    'status' => 'confirmed',
                    'payment_method' => 'mercadopago',
                    'transaction_id' => 'MP123456789',
                    'paid_at' => '2024-12-15 14:30:00',
                    'created_at' => '2024-12-15 14:25:00',
                    'expires_at' => '2025-01-15',
                ],
                [
                    'id' => 2,
                    'company_name' => 'Empresa Demo 2',
                    'plan_name' => 'LITE',
                    'amount' => 2500.00,
                    'currency' => 'ARS',
                    'status' => 'pending',
                    'payment_method' => 'transfer',
                    'transaction_id' => 'TRF987654321',
                    'paid_at' => null,
                    'created_at' => '2024-12-14 10:15:00',
                    'expires_at' => '2025-01-14',
                ],
                [
                    'id' => 3,
                    'company_name' => 'Empresa Demo 3',
                    'plan_name' => 'PRO',
                    'amount' => 4500.00,
                    'currency' => 'ARS',
                    'status' => 'failed',
                    'payment_method' => 'mercadopago',
                    'transaction_id' => 'MP111222333',
                    'paid_at' => null,
                    'created_at' => '2024-12-13 16:45:00',
                    'expires_at' => '2025-01-13',
                ],
                [
                    'id' => 4,
                    'company_name' => 'Empresa Demo 1',
                    'plan_name' => 'PRO',
                    'amount' => 4500.00,
                    'currency' => 'ARS',
                    'status' => 'confirmed',
                    'payment_method' => 'mercadopago',
                    'transaction_id' => 'MP444555666',
                    'paid_at' => '2024-12-12 09:20:00',
                    'created_at' => '2024-12-12 09:15:00',
                    'expires_at' => '2025-01-12',
                ],
            ];

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

            $summary = [
                'total_amount' => 16000.00,
                'confirmed_amount' => 9000.00,
                'pending_amount' => 2500.00,
                'failed_amount' => 4500.00,
                'total_count' => 4,
                'confirmed_count' => 2,
                'pending_count' => 1,
                'failed_count' => 1,
            ];
        }

        // Convertir summary a stats para compatibilidad con la vista
        $stats = [
            'total' => $summary['total_count'] ?? 0,
            'successful' => $summary['confirmed_count'] ?? 0,
            'pending' => $summary['pending_count'] ?? 0,
            'total_amount' => $summary['total_amount'] ?? 0,
        ];

        return view('payments.index', compact(
            'payments', 
            'pagination', 
            'summary',
            'stats', 
            'search', 
            'status', 
            'method', 
            'date_from', 
            'date_to'
        ));
    }

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

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

            // Datos de ejemplo para desarrollo
            $payment = [
                'id' => $id,
                'company_name' => 'Empresa Demo ' . $id,
                'plan_name' => 'PRO',
                'amount' => 4500.00,
                'currency' => 'ARS',
                'status' => 'confirmed',
                'payment_method' => 'mercadopago',
                'transaction_id' => 'MP12345678' . $id,
                'paid_at' => '2024-12-15 14:30:00',
                'created_at' => '2024-12-15 14:25:00',
                'expires_at' => '2025-01-15',
                'details' => [
                    'payer_email' => 'contacto@empresademo' . $id . '.com',
                    'payment_url' => 'https://mercadopago.com/payment/12345678' . $id,
                    'description' => 'Plan PRO - Mes de Enero 2025',
                ],
            ];
        }

        return view('payments.show', compact('payment'));
    }

    /**
     * Update payment status (for manual confirmation).
     */
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:confirmed,failed,cancelled',
            'notes' => 'nullable|string|max:1000',
        ]);

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

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

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

    /**
     * Export payments to CSV.
     */
    public function export(Request $request)
    {
        try {
            $params = $request->only(['search', 'status', 'method', 'date_from', 'date_to']);
            
            $response = $this->apiService->makeApiRequest('GET', '/payments/export', [], $params, 'export_payments');
            
            if ($response && isset($response['success']) && $response['success']) {
                $filename = 'pagos_' . date('Y-m-d_H-i-s') . '.csv';
                
                return response()->streamDownload(function() use ($response) {
                    echo $response['data'];
                }, $filename, [
                    'Content-Type' => 'text/csv',
                ]);
            } else {
                $message = $response['message'] ?? 'Error al exportar';
                return back()->with('error', $message);
            }

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

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