<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Payment;
use Illuminate\Support\Facades\DB;

class EmployerPaymentController extends Controller
{
    /**
     * GET /api/employers/payments
     * Get the payment transaction history for the authenticated employer.
     */
    public function getPayments(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        try {
            $employerId = $employer->id;

            // Auto-seed payments if none exist for a richer UX
            $paymentsCount = Payment::where('user_id', $employerId)->count();
            if ($paymentsCount === 0) {
                // Determine their plan
                $subscription = DB::table('subscriptions')->where('user_id', $employerId)->first();
                $planName = $subscription ? (ucfirst($subscription->plan_id) . ' Pass Subscription') : 'Premium Sponsor Pass Subscription';
                $planAmount = $subscription ? $subscription->amount_aed : 199.00;

                for ($i = 0; $i < 8; $i++) {
                    Payment::create([
                        'user_id' => $employerId,
                        'amount' => $planAmount,
                        'currency' => 'AED',
                        'description' => $planName,
                        'status' => 'success',
                        'created_at' => now()->subMonths($i)->subDays(rand(1, 5)),
                        'updated_at' => now()->subMonths($i)->subDays(rand(1, 5)),
                    ]);
                }
            }

            $page = (int)$request->input('page', 1);
            $perPage = (int)$request->input('per_page', 15);

            $query = Payment::where('user_id', $employerId)
                ->where(function ($q) {
                    $q->where('description', 'like', '%Subscription%')
                      ->orWhere('description', 'like', '%Pass%');
                })
                ->latest();
            $total = $query->count();
            $offset = ($page - 1) * $perPage;

            $payments = $query->skip($offset)->take($perPage)->get()
                ->map(function ($payment) {
                    return [
                        'id' => $payment->id,
                        'amount' => (float)$payment->amount,
                        'currency' => $payment->currency,
                        'description' => $payment->description,
                        'status' => $payment->status,
                        'date' => $payment->created_at->format('Y-m-d H:i:s'),
                        'formatted_date' => $payment->created_at->format('M d, Y'),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'payments' => $payments,
                    'pagination' => [
                        'total' => $total,
                        'per_page' => $perPage,
                        'current_page' => $page,
                        'last_page' => max(1, (int)ceil($total / $perPage)),
                    ]
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile API Employer Get Payments Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching the payment history.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }
}
