<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PaymentMethod;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PaymentMethodController extends Controller
{
    /**
     * Get active payment methods for POS
     */
    public function active()
    {
        try {
            // Get active methods with proper JSON handling
            $methods = PaymentMethod::where('is_active', true)
                ->orderBy('sort_order')
                ->get()
                ->map(function ($method) {
                    return [
                        'id' => $method->id,
                        'code' => $method->code,
                        'name' => $method->name,
                        'type' => $method->type,
                        'provider' => $method->provider,
                        'icon' => $method->icon,
                        'description' => $method->description,
                        'requires_confirmation' => (bool) $method->requires_confirmation,
                        'config' => $method->config ?? [], // Already cast to array in model
                        'color' => $this->getMethodColor($method->code),
                        'sort_order' => $method->sort_order,
                        'is_active' => (bool) $method->is_active,
                    ];
                });

            \Log::info('Loaded payment methods:', ['count' => $methods->count()]);

            return response()->json([
                'success' => true,
                'methods' => $methods,
                'count' => $methods->count(),
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Exception $e) {
            \Log::error('PaymentMethodController error: ' . $e->getMessage(), [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            
            // Return defaults on error
            return response()->json([
                'success' => true,
                'methods' => $this->getDefaultMethods(),
                'count' => 6,
                'error' => config('app.debug') ? $e->getMessage() : null,
                'timestamp' => now()->toISOString()
            ]);
        }
    }
    
    /**
     * Get all payment methods
     */
    public function index(Request $request)
    {
        try {
            $methods = PaymentMethod::orderBy('sort_order')
                ->get()
                ->map(function ($method) {
                    return [
                        'id' => $method->id,
                        'code' => $method->code,
                        'name' => $method->name,
                        'type' => $method->type,
                        'provider' => $method->provider,
                        'icon' => $method->icon,
                        'description' => $method->description,
                        'requires_confirmation' => (bool) $method->requires_confirmation,
                        'config' => $method->config ?? [],
                        'color' => $this->getMethodColor($method->code),
                        'sort_order' => $method->sort_order,
                        'is_active' => (bool) $method->is_active,
                    ];
                });

            return response()->json([
                'success' => true,
                'methods' => $methods,
                'count' => $methods->count()
            ]);
        } catch (\Exception $e) {
            \Log::error('PaymentMethodController index error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to load payment methods',
                'error' => config('app.debug') ? $e->getMessage() : null,
                'methods' => $this->getDefaultMethods()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * Get payment method types
     */
    public function types()
    {
        $types = [
            ['value' => 'cash', 'label' => 'Cash', 'icon' => 'money', 'description' => 'Physical cash payment'],
            ['value' => 'mobile', 'label' => 'Mobile Money', 'icon' => 'mobile-alt', 'description' => 'M-Pesa, Airtel Money'],
            ['value' => 'card', 'label' => 'Card', 'icon' => 'credit-card', 'description' => 'Credit/Debit card payments'],
            ['value' => 'bank', 'label' => 'Bank Transfer', 'icon' => 'bank', 'description' => 'Bank transfers, EFT, RTGS'],
            ['value' => 'credit', 'label' => 'Credit', 'icon' => 'receipt', 'description' => 'Credit sales, Pay later'],
            ['value' => 'digital', 'label' => 'Digital Wallet', 'icon' => 'wallet', 'description' => 'Digital wallet payments'],
        ];
        
        return response()->json([
            'success' => true,
            'types' => $types
        ]);
    }
    
    /**
     * Get specific payment method
     */
    public function show($id)
    {
        try {
            $method = PaymentMethod::find($id);
            
            if (!$method) {
                return response()->json([
                    'success' => false,
                    'message' => 'Payment method not found'
                ], Response::HTTP_NOT_FOUND);
            }
            
            return response()->json([
                'success' => true,
                'method' => [
                    'id' => $method->id,
                    'code' => $method->code,
                    'name' => $method->name,
                    'type' => $method->type,
                    'provider' => $method->provider,
                    'icon' => $method->icon,
                    'description' => $method->description,
                    'requires_confirmation' => (bool) $method->requires_confirmation,
                    'config' => $method->config ?? [],
                    'color' => $this->getMethodColor($method->code),
                    'sort_order' => $method->sort_order,
                    'is_active' => (bool) $method->is_active,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load payment method'
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * Get color for payment method
     */
    private function getMethodColor($code)
    {
        $colors = [
            'cash' => '#28a745', // Green
            'mpesa' => '#4facfe', // Light Blue
            'card' => '#007bff', // Blue
            'credit' => '#ffc107', // Yellow
            'multiple' => '#6f42c1', // Purple
            'bank' => '#20c997', // Teal
            'cheque' => '#17a2b8', // Cyan
            'airtel' => '#fd7e14', // Orange
            'split' => '#9b59b6', // Purple
        ];
        
        return $colors[$code] ?? '#6c757d'; // Default gray
    }
    
    /**
     * Get default payment methods (fallback)
     */
    private function getDefaultMethods()
    {
        return [
            [
                'id' => 1,
                'code' => 'cash',
                'name' => 'Cash',
                'type' => 'cash',
                'icon' => 'money',
                'color' => '#28a745',
                'description' => 'Physical cash payment',
                'requires_confirmation' => false,
                'config' => [],
                'sort_order' => 1,
                'is_active' => true,
            ],
            [
                'id' => 2,
                'code' => 'mpesa',
                'name' => 'M-Pesa',
                'type' => 'mobile',
                'provider' => 'mpesa',
                'icon' => 'mobile-alt',
                'color' => '#4facfe',
                'description' => 'Mobile money payment',
                'requires_confirmation' => true,
                'config' => ['stk_push_enabled' => true, 'manual_entry_enabled' => true],
                'sort_order' => 2,
                'is_active' => true,
            ],
            [
                'id' => 3,
                'code' => 'card',
                'name' => 'Card',
                'type' => 'card',
                'icon' => 'credit-card',
                'color' => '#007bff',
                'description' => 'Credit/Debit card',
                'requires_confirmation' => true,
                'config' => ['supported_types' => ['visa', 'mastercard', 'amex']],
                'sort_order' => 3,
                'is_active' => true,
            ],
            [
                'id' => 4,
                'code' => 'credit',
                'name' => 'Credit',
                'type' => 'credit',
                'icon' => 'receipt',
                'color' => '#ffc107',
                'description' => 'Pay later',
                'requires_confirmation' => true,
                'config' => ['default_terms' => 30, 'max_terms' => 90],
                'sort_order' => 4,
                'is_active' => true,
            ],
            [
                'id' => 5,
                'code' => 'multiple',
                'name' => 'Split Payment',
                'type' => 'multiple',
                'icon' => 'layer',
                'color' => '#6f42c1',
                'description' => 'Multiple payment methods',
                'requires_confirmation' => false,
                'config' => ['max_methods' => 3],
                'sort_order' => 5,
                'is_active' => true,
            ],
        ];
    }
}