<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\CardDeliveryController;
use App\Models\EasypaisaCustomer;
use App\Models\Subscription;
use Illuminate\Http\JsonResponse;
use App\Traits\ChecksProfileComplete;
use Illuminate\Http\Request; // ← ADD THIS



class CustomerDashboardController extends Controller
{
    use ChecksProfileComplete;
    // =========================================================================
    //  GET /api/v1/dashboard/{open_id}
    //
    //  Called when Easypaisa opens the iframe — open_id is passed in the URL.
    //
    //  Returns:
    //   1. customer         — name, DOB, contact info
    //   2. policy_status    — active / pending / none
    //   3. policy_card      — cert, dates, coverage summary
    //   4. dependents       — all insured members except self
    //   5. plan_benefits    — full product coverage breakdown
    // =========================================================================

    public function show(Request $request, string $open_id): JsonResponse
{
    // ── 1. Find customer by open_id ───────────────────────────────────────
    $customer = EasypaisaCustomer::where('open_id', $open_id)->first();
    
    if (!$customer) {
        return response()->json([
            'status'  => 404,
            'message' => 'No customer found for the provided open_id.',
        ], 404);
    }

        // ── 2. Load most recent active subscription ───────────────────────────
        //      Falls back to latest pending, then any latest subscription
        $subscription = Subscription::where('customer_id', $customer->customer_id)
            ->with([
                'plan',
                'product',
                'members' => fn($q) => $q->orderByRaw("FIELD(member_type,'self','spouse','son','daughter')")
            ])
            ->orderByRaw("FIELD(policy_status,'active','pending_payment','grace_period','expired','cancelled','failed','suspended')")
            ->orderBy('created_at', 'desc')
            ->first();

        return response()->json([
            'status' => 200,
            'data'   => [
                'customer'      => $this->buildCustomerBlock($customer),
                'policy_status' => $this->buildPolicyStatusBlock($subscription),
                'policy_card'   => $this->buildPolicyCard($subscription),
                'dependents'    => $this->buildDependents($subscription),
                'plan_benefits' => $this->buildPlanBenefits($subscription),
                'physical_card' => (new CardDeliveryController)->buildCardBlock($customer),
            ],
        ], 200);
    }

    // =========================================================================
    //  BLOCK BUILDERS
    // =========================================================================

    private function buildCustomerBlock(EasypaisaCustomer $customer): array
    {
        return [
            'customer_id'   => $customer->customer_id,
            'full_name'     => $customer->full_name,
            'dob'           => $customer->dob?->format('Y-m-d'),
            'gender'        => $customer->gender,
            'msisdn'        => $customer->msisdn,
            'email'         => $customer->email,
            'cnic'          => $customer->masked_cnic,  // masked: *****-***XXXX-*
            'city'          => $customer->city,
            'is_verified'   => $customer->is_verified,
            'is_easypaisa_verified' => $customer->is_easypaisa_verified,
            'user_avatar'   => $customer->user_avatar,
            'profile_complete'      => $this->checkProfileComplete($customer), 
        ];
    }

    private function buildPolicyStatusBlock(?Subscription $subscription): array
    {
        if (!$subscription) {
            return [
                'has_policy'          => false,
                'policy_status'       => null,
                'policy_status_label' => 'No Policy',
                'is_active'           => false,
                'message'             => 'No subscription found. Purchase a plan to get covered.',
            ];
        }

        $statusLabels = [
            'pending_payment' => 'Pending Payment',
            'active'          => 'Active',
            'expired'         => 'Expired',
            'cancelled'       => 'Cancelled',
            'failed'          => 'Payment Failed',
            'grace_period'    => 'Grace Period',
            'suspended'       => 'Suspended',
        ];

        $messages = [
            'pending_payment' => 'Your payment is being processed. Policy will activate shortly.',
            'active'          => 'Your policy is active and you are covered.',
            'expired'         => 'Your policy has expired. Please renew to continue coverage.',
            'cancelled'       => 'Your policy has been cancelled.',
            'failed'          => 'Payment failed. Please retry to activate your policy.',
            'grace_period'    => 'Your policy is in grace period. Please renew immediately.',
            'suspended'       => 'Your policy has been suspended. Please contact support.',
        ];

        return [
            'has_policy'          => true,
            'policy_status'       => $subscription->policy_status,
            'policy_status_label' => $statusLabels[$subscription->policy_status] ?? ucfirst($subscription->policy_status),
            'is_active'           => $subscription->policy_status === 'active',
            'message'             => $messages[$subscription->policy_status] ?? '',
        ];
    }

    private function buildPolicyCard(?Subscription $subscription): ?array
    {
        if (!$subscription) {
            return null;
        }

        $product = $subscription->product;
        $plan    = $subscription->plan;

        // Self member for individual coverage display
        $selfMember = $subscription->members->firstWhere('member_type', 'self');

        return [
            // ── Identifiers ───────────────────────────────────────────────
            'subscription_id'    => $subscription->subscription_id,
            'reference_id'       => $subscription->reference_id,
            'cert_id'            => $subscription->cert_id,
            'policy_number'      => $subscription->policy_number,

            // ── Plan & variant ────────────────────────────────────────────
            'plan_name'          => $plan?->plan_name,
            'brand_name'         => $plan?->highlight_brand_name,
            'variant'            => $subscription->variant,
            'variant_label'      => ucfirst($subscription->variant),
            'efu_product_name'   => $subscription->efu_product_name,

            // ── Coverage ──────────────────────────────────────────────────
            'coverage_per_person_pkr' => $product ? (float) $product->coverage_per_person : null,
            'coverage_per_person_fmt' => $product
                ? 'Rs. ' . number_format($product->coverage_per_person, 0) . '/-'
                : null,
            'cashless_hospitalization' => $product?->cashless_hospitalization,
            'room_board_type'          => $product?->room_board_type,
            'room_board_label'         => $this->roomBoardLabel($product?->room_board_type),

            // ── Premium ───────────────────────────────────────────────────
            'total_premium_pkr'  => (float) ($subscription->total_premium ?? $subscription->premium),
            'total_premium_fmt'  => 'Rs. ' . number_format($subscription->total_premium ?? $subscription->premium, 0) . '/- Yearly',
            'members_count'      => $subscription->members_count ?? 1,
            'age_group'          => $selfMember?->contribution_age_group ?? $subscription->contribution_age_group,

            // ── Dates ─────────────────────────────────────────────────────
            'coverage_start_date'   => $subscription->coverage_start_date?->format('Y-m-d'),
            'coverage_end_date'     => $subscription->coverage_end_date?->format('Y-m-d'),
            'expiry_date'           => $subscription->expiry_date?->format('Y-m-d'),
            'grace_period_end_date' => $subscription->grace_period_end_date?->format('Y-m-d'),
            'activated_at'          => $subscription->activated_at?->toISOString(),

            // ── Days remaining ────────────────────────────────────────────
            'days_remaining' => $subscription->expiry_date && $subscription->policy_status === 'active'
                ? max(0, now()->diffInDays($subscription->expiry_date, false))
                : null,
        ];
    }

    private function buildDependents(?Subscription $subscription): array
    {
        if (!$subscription || $subscription->members->isEmpty()) {
            return [];
        }

        return $subscription->members
            ->where('member_type', '!=', 'self')
            ->values()
            ->map(fn($m) => [
                'member_id'    => $m->member_id,
                'full_name'    => $m->full_name,
                'relationship' => $m->member_type,
                'relationship_label' => ucfirst($m->member_type),
                'dob'          => $m->dob?->format('Y-m-d'),
                'age_in_years' => $m->age_in_years,
                'gender'       => $m->gender,
                'cnic'         => $m->cnic,
                'mobile'       => $m->mobile,
                'premium_fmt'  => 'Rs. ' . number_format($m->premium, 0) . '/- Yearly',
                'age_group'    => $m->contribution_age_group,
            ])
            ->toArray();
    }

    private function buildPlanBenefits(?Subscription $subscription): ?array
    {
        if (!$subscription || !$subscription->product) {
            return null;
        }

        $p    = $subscription->product;
        $plan = $subscription->plan;

        return [
            // ── Core coverage ─────────────────────────────────────────────
            'hospitalization' => [
                'coverage_per_person_pkr' => (float) $p->coverage_per_person,
                'coverage_per_person_fmt' => 'Rs. ' . number_format($p->coverage_per_person, 0) . '/-',
                'cashless'                => $p->cashless_hospitalization,
                'room_board_type'         => $p->room_board_type,
                'room_board_label'        => $this->roomBoardLabel($p->room_board_type),
                'icu_coverage'            => $p->icu_coverage,
            ],

            // ── Pre & Post hospitalization ────────────────────────────────
            'pre_post_hospitalization' => [
                'days'          => $p->pre_post_hospitalization_days,
                'sub_limit_pkr' => (float) $p->pre_post_sub_limit,
                'sub_limit_fmt' => 'Rs. ' . number_format($p->pre_post_sub_limit, 0) . '/-',
            ],

            // ── Emergency outpatient ──────────────────────────────────────
            'emergency_outpatient' => [
                'sub_limit_pkr' => (float) $p->emergency_outpatient_sub_limit,
                'sub_limit_fmt' => 'Rs. ' . number_format($p->emergency_outpatient_sub_limit, 0) . '/-',
            ],

            // ── Additional accident ───────────────────────────────────────
            'additional_accident' => [
                'coverage_pkr' => (float) $p->additional_accident_coverage,
                'coverage_fmt' => 'Rs. ' . number_format($p->additional_accident_coverage, 0) . '/-',
            ],

            // ── Accidental death ──────────────────────────────────────────
            'accidental_death_benefit' => [
                'coverage_pkr' => (float) $p->accidental_death_benefit,
                'coverage_fmt' => 'Rs. ' . number_format($p->accidental_death_benefit, 0) . '/-',
            ],

            // ── Ambulance ─────────────────────────────────────────────────
            'local_ambulance_covered' => $p->local_ambulance_covered,

            // ── Pre-existing conditions ───────────────────────────────────
            'pre_existing_coverage' => [
                'year_1_pct' => $p->pre_existing_year1_pct,
                'year_2_pct' => $p->pre_existing_year2_pct,
                'year_3_pct' => $p->pre_existing_year3_pct,
                'note'       => 'Pre-existing conditions covered progressively over 3 years',
            ],

            // ── Plan highlight features ───────────────────────────────────
            'highlight_features' => $plan?->highlight_features ?? [],
            'plan_description'   => $plan?->plan_description,
        ];
    }

    // =========================================================================
    //  HELPERS
    // =========================================================================

    private function roomBoardLabel(?string $type): ?string
    {
        return match ($type) {
            'private'      => 'Private Room',
            'semi_private' => 'Semi-Private Room',
            'general'      => 'General Ward',
            default        => null,
        };
    }
}