<?php

namespace App\Http\Controllers\Api\Vendor;

use App\Http\Controllers\Controller;
use App\Models\VendorApplication;
use App\Services\ImageService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApplicationController extends Controller
{
    public function __construct(private ImageService $images) {}

    /**
     * GET /api/vendor/applications/{id}
     * Public — vendor checks own status. The application_id is the only
     * identifier the not-yet-authenticated vendor has.
     */
    public function show(int $id): JsonResponse
    {
        $app = VendorApplication::with('category')->findOrFail($id);

        return response()->json([
            'application'      => $app,
            'completed_steps'  => $app->completedSteps(),
            'total_steps'      => 6,
        ]);
    }

    /**
     * Step 2: Upload CNIC front + back (and basic personal info).
     * Multipart POST with cnic, cnic_front, cnic_back files.
     */
    public function uploadCnic(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'cnic'       => 'required|string|regex:/^[0-9]{5}-[0-9]{7}-[0-9]{1}$/',
            'cnic_front' => 'required|image|max:5120',
            'cnic_back'  => 'required|image|max:5120',
        ]);

        $app = VendorApplication::findOrFail($id);
        abort_if(! $app->step1_phone_verified, 422, 'Verify phone first.');

        // Delete old uploads if re-submitting
        $this->images->deletePrivate('vendor_docs', $app->cnic_front_path);
        $this->images->deletePrivate('vendor_docs', $app->cnic_back_path);

        $frontPath = $this->images->storePrivate($request->file('cnic_front'), 'vendor_docs', "applications/{$id}/cnic");
        $backPath  = $this->images->storePrivate($request->file('cnic_back'), 'vendor_docs', "applications/{$id}/cnic");

        $app->update([
            'cnic'                 => $request->cnic,
            'cnic_front_path'      => $frontPath,
            'cnic_back_path'       => $backPath,
            'step2_cnic_uploaded'  => true,
            'current_step'         => max($app->current_step, 3),
        ]);

        return response()->json(['message' => 'CNIC uploaded.', 'application' => $app]);
    }

    /**
     * Step 3: Business info (name, address, locality, category, type).
     */
    public function submitBusinessInfo(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'business_name' => 'required|string|max:150',
            'owner_name'    => 'required|string|max:100',
            'email'         => 'nullable|email|max:150',
            'address'       => 'required|string|max:500',
            'locality'      => 'required|string|max:100',
            'category_id'   => 'required|exists:categories,id',
            'business_type' => 'required|in:shop,home_based,pharmacy,wholesale,restaurant',
        ]);

        $app = VendorApplication::findOrFail($id);
        abort_if(! $app->step2_cnic_uploaded, 422, 'Complete previous steps first.');

        $app->update($request->only([
            'business_name', 'owner_name', 'email',
            'address', 'locality', 'category_id', 'business_type',
        ]) + [
            'step3_business_info_complete' => true,
            'current_step'                 => max($app->current_step, 4),
        ]);

        return response()->json(['message' => 'Business info saved.', 'application' => $app]);
    }

    /**
     * Step 4: Business proof (trade licence / shop photo / utility bill / rent agreement).
     */
    public function uploadBusinessProof(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'business_proof' => 'required|image|max:5120',
        ]);

        $app = VendorApplication::findOrFail($id);
        abort_if(! $app->step3_business_info_complete, 422, 'Complete previous steps first.');

        $this->images->deletePrivate('vendor_docs', $app->business_proof_path);

        $path = $this->images->storePrivate(
            $request->file('business_proof'),
            'vendor_docs',
            "applications/{$id}/proof"
        );

        $app->update([
            'business_proof_path'           => $path,
            'step4_business_proof_uploaded' => true,
            'current_step'                  => max($app->current_step, 5),
        ]);

        return response()->json(['message' => 'Business proof uploaded.', 'application' => $app]);
    }

    /**
     * Step 5: Selfie holding CNIC (liveness check — admin reviews manually).
     */
    public function uploadSelfie(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'selfie' => 'required|image|max:5120',
        ]);

        $app = VendorApplication::findOrFail($id);
        abort_if(! $app->step4_business_proof_uploaded, 422, 'Complete previous steps first.');

        $this->images->deletePrivate('vendor_docs', $app->selfie_with_cnic_path);

        $path = $this->images->storePrivate(
            $request->file('selfie'),
            'vendor_docs',
            "applications/{$id}/selfie"
        );

        $app->update([
            'selfie_with_cnic_path' => $path,
            'step5_selfie_uploaded' => true,
            'current_step'          => max($app->current_step, 6),
        ]);

        return response()->json(['message' => 'Selfie uploaded.', 'application' => $app]);
    }

    /**
     * Step 6: Bank / wallet settlement details.
     */
    public function submitBankDetails(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'settlement_method'         => 'required|in:bank,easypaisa,jazzcash',
            'settlement_account_name'   => 'required|string|max:100',
            'settlement_account_number' => 'required|string|max:50',
        ]);

        $app = VendorApplication::findOrFail($id);
        abort_if(! $app->step5_selfie_uploaded, 422, 'Complete previous steps first.');

        $app->update($request->only([
            'settlement_method',
            'settlement_account_name',
            'settlement_account_number',
        ]) + [
            'step6_bank_details_complete' => true,
            'current_step'                => 7,
        ]);

        return response()->json(['message' => 'Bank details saved.', 'application' => $app]);
    }

    /**
     * Final submit — moves application to under_review queue for admin.
     */
    public function submitForReview(int $id): JsonResponse
    {
        $app = VendorApplication::findOrFail($id);

        $required = [
            'step1_phone_verified',
            'step2_cnic_uploaded',
            'step3_business_info_complete',
            'step4_business_proof_uploaded',
            'step5_selfie_uploaded',
            'step6_bank_details_complete',
        ];

        foreach ($required as $step) {
            if (! $app->{$step}) {
                return response()->json([
                    'message'        => 'Some steps are incomplete.',
                    'missing_step'   => $step,
                ], 422);
            }
        }

        abort_if(
            in_array($app->status, ['submitted', 'under_review', 'approved'], true),
            422,
            'Application already submitted.'
        );

        $app->update([
            'status'       => 'submitted',
            'current_step' => 7,
        ]);

        return response()->json([
            'message'     => 'Application submitted for review. You will hear from us in 1–3 business days.',
            'application' => $app,
        ]);
    }
}
