<?php

namespace App\Http\Controllers\Api\V1\Immigopro;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\ImmigoProSubscription;
use App\Models\ImmigoProQuotationAnswer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class MarketingOfficerUserDetailController extends Controller
{
    /**
     * Get complete user details for marketing officers
     * This endpoint takes a user ID (not subscription ID)
     */
    public function getUserDetails($userId): JsonResponse
    {
        try {
            \Log::info('MarketingOfficerUserDetailController: getUserDetails called', ['user_id' => $userId]);
            
            $marketingOfficer = Auth::user();
            \Log::info('Marketing officer authenticated', [
                'officer_id' => $marketingOfficer?->id,
                'officer_email' => $marketingOfficer?->email
            ]);
            
            // Verify user is a marketing officer or super admin
            if (!$marketingOfficer->hasRole('marketing_officer') && !$marketingOfficer->hasRole('super_admin')) {
                \Log::warning('User does not have required role');
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 403);
            }

            \Log::info('Role check passed');

            // If marketing officer, verify this user is assigned to them
            if ($marketingOfficer->hasRole('marketing_officer') && !$marketingOfficer->hasRole('super_admin')) {
                \Log::info('Checking user assignment', [
                    'officer_id' => $marketingOfficer->id,
                    'target_user_id' => $userId
                ]);
                
                $isAssigned = DB::table('marketing_officer_users')
                    ->where('marketing_officer_id', $marketingOfficer->id)
                    ->where('user_id', $userId)
                    ->exists();
                
                \Log::info('Assignment check result', ['is_assigned' => $isAssigned]);
                    
                if (!$isAssigned) {
                    \Log::warning('User not assigned to this marketing officer');
                    return response()->json([
                        'success' => false,
                        'message' => 'You do not have access to this user'
                    ], 403);
                }
            }

            \Log::info('Fetching user details from database');
            // Get user details
            $user = User::findOrFail($userId);

            // Get the user's subscription (if exists)
            $subscription = ImmigoProSubscription::where('user_id', $userId)
                ->orderBy('created_at', 'desc')
                ->first();

            // Get quotation answers
            $answers = ImmigoProQuotationAnswer::with(['question'])
                ->where('user_id', $userId)
                ->get()
                ->map(function ($answer) {
                    return [
                        'id' => $answer->id,
                        'answer' => $answer->answer,
                        'question' => [
                            'id' => $answer->question->id,
                            'question_text' => $answer->question->question ?? $answer->question->question_text,
                            'question_type' => $answer->question->type,
                            'options' => $answer->question->options,
                        ],
                        'created_at' => $answer->created_at,
                        'updated_at' => $answer->updated_at,
                    ];
                });

            // Get payment details if subscription exists
            $payments = [];
            if ($subscription) {
                $payments = DB::table('immigopro_installment_payments')
                    ->where('subscription_id', $subscription->id)
                    ->orderBy('installment_number', 'asc')
                    ->get()
                    ->map(function ($payment) {
                        return [
                            'id' => $payment->id,
                            'installment_number' => $payment->installment_number,
                            'amount' => $payment->amount,
                            'status' => $payment->status,
                            'paid_at' => $payment->paid_at,
                            'stripe_payment_intent_id' => $payment->stripe_payment_intent_id,
                        ];
                    });
            }

            $responseData = [
                'user' => [
                    'id' => $user->id,
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'name' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone ?? null,
                    'license_number' => $user->license_number ?? null,
                    'user_category' => $user->user_category,
                    'user_type' => $user->user_type,
                    'status' => $user->status,
                    'created_at' => $user->created_at,
                ],
                'quotation_answers' => $answers,
                'payments' => $payments,
            ];

            // Add subscription data if it exists
            if ($subscription) {
                $responseData['subscription'] = [
                    'id' => $subscription->id,
                    'user_id' => $subscription->user_id,
                    'package_name' => $subscription->package_name,
                    'payment_plan' => $subscription->payment_plan,
                    'status' => $subscription->status,
                    'activated_at' => $subscription->activated_at,
                    'license_key' => $subscription->license_key,
                    'base_price' => $subscription->base_price,
                    'upfront_amount' => $subscription->upfront_amount,
                    'monthly_amount' => $subscription->monthly_amount,
                    'total_amount' => $subscription->total_amount,
                    'tax_amount' => $subscription->tax_amount,
                    'installments' => $subscription->installments,
                    'paid_installments' => $subscription->paid_installments,
                    'next_charge_date' => $subscription->next_charge_date,
                ];
            } else {
                // No subscription yet
                $responseData['subscription'] = null;
            }

            return response()->json($responseData);
        } catch (\Exception $e) {
            \Log::error('Error in getUserDetails', [
                'user_id' => $userId,
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'message' => 'Failed to fetch user details',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
