<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\EasypaisaCustomer;
use App\Models\Subscription;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CardDeliveryController extends Controller
{
    // =========================================================================
    //  POST /api/v1/card-delivery/{open_id}/request
    //
    //  Customer submits delivery address — triggers card request.
    //  Guards:
    //   - Customer must exist
    //   - Customer must have an active subscription
    //   - Card must not already be delivered
    // =========================================================================

    // public function requestCard(Request $request, string $openId): JsonResponse
    // {
    //     $customer = EasypaisaCustomer::where('open_id', $openId)->first();

    //     if (!$customer) {
    //         return response()->json([
    //             'status'  => 404,
    //             'message' => 'No customer found for the provided open_id.',
    //         ], 404);
    //     }

    //     // ── Guard: must have active policy to request a card ──────────────────
    //     $hasActivePolicy = Subscription::where('customer_id', $customer->customer_id)
    //         ->where('policy_status', 'active')
    //         ->exists();

    //     if (!$hasActivePolicy) {
    //         return response()->json([
    //             'status'  => 422,
    //             'message' => 'No active policy found. Please activate your policy before requesting a physical card.',
    //         ], 422);
    //     }

    //     // ── Guard: already delivered ──────────────────────────────────────────
    //     if ($customer->card_delivered) {
    //         return response()->json([
    //             'status'       => 409,
    //             'message'      => 'Your physical card has already been delivered.',
    //             'card_status'  => $customer->card_status,
    //             'delivered_at' => $customer->card_delivered_at?->toISOString(),
    //         ], 409);
    //     }

    //     // ── Guard: already requested / in progress ────────────────────────────
    //     if (in_array($customer->card_status, ['printing', 'dispatched'])) {
    //         return response()->json([
    //             'status'      => 409,
    //             'message'     => 'Your card is already ' . $customer->card_status . '. Please wait for delivery.',
    //             'card_status' => $customer->card_status,
    //             'tracking'    => $customer->courier_tracking_number,
    //         ], 409);
    //     }

    //     $request->validate([
    //         'delivery_full_name'  => 'required|string|max:150',
    //         'delivery_mobile'     => 'required|string|max:20',
    //         'delivery_address'    => 'required|string|max:500',
    //         'delivery_city'       => 'required|string|max:100',
    //         'delivery_province'   => 'required|string|max:100',
    //         'delivery_postal_code'=> 'nullable|string|max:10',
    //     ]);

    //     $customer->update([
    //         'card_status'          => 'requested',
    //         'card_delivered'       => false,
    //         'card_requested_at'    => now(),
    //         'delivery_full_name'   => $request->input('delivery_full_name'),
    //         'delivery_mobile'      => $request->input('delivery_mobile'),
    //         'delivery_address'     => $request->input('delivery_address'),
    //         'delivery_city'        => $request->input('delivery_city'),
    //         'delivery_province'    => $request->input('delivery_province'),
    //         'delivery_postal_code' => $request->input('delivery_postal_code'),
    //     ]);

    //     Log::info('CardDeliveryController@requestCard: Card requested.', [
    //         'customer_id' => $customer->customer_id,
    //         'city'        => $request->input('delivery_city'),
    //     ]);

    //     return response()->json([
    //         'status'  => 200,
    //         'message' => 'Physical card request submitted successfully. We will dispatch your card soon.',
    //         'data'    => $this->buildCardBlock($customer->fresh()),
    //     ], 200);
    // }
    
    public function requestCard(Request $request): JsonResponse
{
    $request->validate([
        'open_id'              => 'required|string',
        'delivery_full_name'   => 'required|string|max:150',
        'delivery_mobile'      => 'required|string|max:20',
        'delivery_address'     => 'required|string|max:500',
        'delivery_city'        => 'required|string|max:100',
        'delivery_province'    => 'required|string|max:100',
        'delivery_postal_code' => 'nullable|string|max:10',
    ]);

    $customer = EasypaisaCustomer::where('open_id', $request->input('open_id'))->first();
    if (!$customer) {
        return response()->json([
            'status'  => 404,
            'message' => 'No customer found for the provided open_id.',
        ], 404);
    }

    // ── Guard: must have active policy ────────────────────────────────────
    $hasActivePolicy = Subscription::where('customer_id', $customer->customer_id)
        ->where('policy_status', 'active')
        ->exists();
    if (!$hasActivePolicy) {
        return response()->json([
            'status'  => 422,
            'message' => 'No active policy found. Please activate your policy before requesting a physical card.',
        ], 422);
    }

    // ── Guard: already delivered ──────────────────────────────────────────
    if ($customer->card_delivered) {
        return response()->json([
            'status'       => 409,
            'message'      => 'Your physical card has already been delivered.',
            'card_status'  => $customer->card_status,
            'delivered_at' => $customer->card_delivered_at?->toISOString(),
        ], 409);
    }

    // ── Guard: already in progress ────────────────────────────────────────
    if (in_array($customer->card_status, ['printing', 'dispatched'])) {
        return response()->json([
            'status'      => 409,
            'message'     => 'Your card is already ' . $customer->card_status . '. Please wait for delivery.',
            'card_status' => $customer->card_status,
            'tracking'    => $customer->courier_tracking_number,
        ], 409);
    }

    $customer->update([
        'card_status'          => 'requested',
        'card_delivered'       => false,
        'card_requested_at'    => now(),
        'delivery_full_name'   => $request->input('delivery_full_name'),
        'delivery_mobile'      => $request->input('delivery_mobile'),
        'delivery_address'     => $request->input('delivery_address'),
        'delivery_city'        => $request->input('delivery_city'),
        'delivery_province'    => $request->input('delivery_province'),
        'delivery_postal_code' => $request->input('delivery_postal_code'),
    ]);

    Log::info('CardDeliveryController@requestCard: Card requested.', [
        'customer_id' => $customer->customer_id,
        'city'        => $request->input('delivery_city'),
    ]);

    return response()->json([
        'status'  => 200,
        'message' => 'Physical card request submitted successfully. We will dispatch your card soon.',
        'data'    => $this->buildCardBlock($customer->fresh()),
    ], 200);
}

    // =========================================================================
    //  PUT /api/v1/card-delivery/{open_id}/address
    //
    //  Update delivery address — allowed only when card is not_requested or requested.
    // =========================================================================

    public function updateAddress(Request $request, string $openId): JsonResponse
    {
        $customer = EasypaisaCustomer::where('open_id', $openId)->first();

        if (!$customer) {
            return response()->json([
                'status'  => 404,
                'message' => 'No customer found for the provided open_id.',
            ], 404);
        }

        // ── Guard: cannot change address once card is printing/dispatched ─────
        if (in_array($customer->card_status, ['printing', 'dispatched', 'delivered'])) {
            return response()->json([
                'status'      => 422,
                'message'     => 'Address cannot be changed. Card is already ' . $customer->card_status . '.',
                'card_status' => $customer->card_status,
            ], 422);
        }

        $request->validate([
            'delivery_full_name'  => 'required|string|max:150',
            'delivery_mobile'     => 'required|string|max:20',
            'delivery_address'    => 'required|string|max:500',
            'delivery_city'       => 'required|string|max:100',
            'delivery_province'   => 'required|string|max:100',
            'delivery_postal_code'=> 'nullable|string|max:10',
        ]);

        $customer->update([
            'delivery_full_name'   => $request->input('delivery_full_name'),
            'delivery_mobile'      => $request->input('delivery_mobile'),
            'delivery_address'     => $request->input('delivery_address'),
            'delivery_city'        => $request->input('delivery_city'),
            'delivery_province'    => $request->input('delivery_province'),
            'delivery_postal_code' => $request->input('delivery_postal_code'),
        ]);

        return response()->json([
            'status'  => 200,
            'message' => 'Delivery address updated successfully.',
            'data'    => $this->buildCardBlock($customer->fresh()),
        ], 200);
    }

    // =========================================================================
    //  PATCH /api/v1/card-delivery/{open_id}/status   [Admin use]
    //
    //  Admin updates card status: printing → dispatched → delivered
    // =========================================================================

    public function updateStatus(Request $request, string $openId): JsonResponse
    {
        $customer = EasypaisaCustomer::where('open_id', $openId)->first();

        if (!$customer) {
            return response()->json([
                'status'  => 404,
                'message' => 'No customer found.',
            ], 404);
        }

        $request->validate([
            'card_status'             => 'required|in:printing,dispatched,delivered,returned',
            'courier_tracking_number' => 'nullable|string|max:150',
        ]);

        $newStatus = $request->input('card_status');

        $updates = ['card_status' => $newStatus];

        if ($newStatus === 'dispatched') {
            $updates['card_dispatched_at']       = now();
            $updates['courier_tracking_number']  = $request->input('courier_tracking_number');
        }

        if ($newStatus === 'delivered') {
            $updates['card_delivered']    = true;
            $updates['card_delivered_at'] = now();
        }

        $customer->update($updates);

        Log::info('CardDeliveryController@updateStatus: Status updated.', [
            'customer_id' => $customer->customer_id,
            'card_status' => $newStatus,
        ]);

        return response()->json([
            'status'  => 200,
            'message' => 'Card status updated to: ' . $newStatus,
            'data'    => $this->buildCardBlock($customer->fresh()),
        ], 200);
    }

    // =========================================================================
    //  HELPER — reusable card block
    // =========================================================================

    public function buildCardBlock(EasypaisaCustomer $customer): array
    {
        $statusLabels = [
            'not_requested' => 'Not Requested',
            'requested'     => 'Requested',
            'printing'      => 'In Printing',
            'dispatched'    => 'Dispatched',
            'delivered'     => 'Delivered',
            'returned'      => 'Returned',
        ];

        return [
            // ── Status ────────────────────────────────────────────────────
            'card_status'       => $customer->card_status,
            'card_status_label' => $statusLabels[$customer->card_status] ?? ucfirst($customer->card_status),
            'card_delivered'    => $customer->card_delivered,

            // ── Timestamps ────────────────────────────────────────────────
            'card_requested_at' => $customer->card_requested_at?->toISOString(),
            'card_dispatched_at'=> $customer->card_dispatched_at?->toISOString(),
            'card_delivered_at' => $customer->card_delivered_at?->toISOString(),

            // ── Tracking ──────────────────────────────────────────────────
            'courier_tracking_number' => $customer->courier_tracking_number,

            // ── Delivery address ──────────────────────────────────────────
            'delivery_address' => $customer->delivery_address ? [
                'full_name'   => $customer->delivery_full_name,
                'mobile'      => $customer->delivery_mobile,
                'address'     => $customer->delivery_address,
                'city'        => $customer->delivery_city,
                'province'    => $customer->delivery_province,
                'postal_code' => $customer->delivery_postal_code,
            ] : null,
        ];
    }
}