<?php

namespace App\Http\Controllers\Employer;

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

class PaymentController extends Controller
{
    private function resolveCurrentUser()
    {
        $sess = session('user');
        $sessId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
        
        if (!$sessId) {
            $user = User::where('role', 'employer')->first();
            if ($user) {
                session(['user' => (object)[
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => 'employer',
                    'subscription_status' => $user->subscription_status ?? 'active',
                ]]);
                return $user;
            }
        } else {
            return User::find($sessId);
        }
        
        return null;
    }

    public function index(Request $request)
    {
        $user = $this->resolveCurrentUser();
        $employerId = $user ? $user->id : 2;

        // Auto-seed payments if none exist for a richer UX
        $paymentsCount = Payment::where('user_id', $employerId)->count();
        if ($paymentsCount === 0) {
            $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)),
                ]);
            }
        }

        $payments = Payment::where('user_id', $employerId)
            ->where(function ($q) {
                $q->where('description', 'like', '%Subscription%')
                  ->orWhere('description', 'like', '%Pass%');
            })
            ->latest()
            ->get()
            ->map(function ($p) {
                return [
                    'id' => $p->id,
                    'amount' => (float)$p->amount,
                    'currency' => $p->currency,
                    'description' => $p->description,
                    'status' => $p->status,
                    'date' => $p->created_at->format('M d, Y'),
                    'time' => $p->created_at->format('h:i A'),
                    'invoice_no' => 'INV-' . str_pad($p->id, 6, '0', STR_PAD_LEFT),
                ];
            })->toArray();

        // Retrieve subscription details for billing and renewal analytics
        $sub = DB::table('subscriptions')->where('user_id', $employerId)->where('status', 'active')->latest('id')->first();
        $expiresAt = $sub && $sub->expires_at ? date('M d, Y', strtotime($sub->expires_at)) : 'Dec 31, 2026';
        $currentPlan = $sub ? (ucfirst($sub->plan_id) . ' Sponsor Pass') : 'Premium Sponsor Pass';
        $subStatus = $user && $user->subscription_status ? ucfirst($user->subscription_status) : 'Active';

        return Inertia::render('Employer/PaymentHistory', [
            'payments' => $payments,
            'currentPlan' => $currentPlan,
            'expiresAt' => $expiresAt,
            'subscriptionStatus' => $subStatus,
        ]);
    }
}
