<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\VevsClient;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException;

class VevsImportController extends Controller
{
    public function fetch(Request $request)
    {
        $data = $request->validate([
            'ref_id' => ['required', 'string', 'regex:/^[A-Za-z0-9_-]+$/'],
        ]);

        try {
            $res = VevsClient::make()->getReservation($data['ref_id']);

            // Map VEVS payload → your form fields
            $fields = [
                // basic job fields on your form
                'booking_reference'      => $res['ref_id'] ?? $res['booking_id'] ?? null,
                'pickup_at'              => $res['from']    ?? null,
                'return_at'              => $res['to']      ?? null,
                'vehicle_id'             => isset($res['car_id']) ? (int) $res['car_id'] : null,
                'pickup_location_id'     => isset($res['pickup_id']) ? (int) $res['pickup_id'] : null,
                'return_location_id'     => isset($res['return_id']) ? (int) $res['return_id'] : null,
                'total_price'            => $res['total_price']      ?? null,
                'required_deposit'       => $res['required_deposit'] ?? null,
                'security_deposit'       => $res['security_deposit'] ?? null,

                // suggested defaults for selects
                // adjust keys to match your actual select names/ids
                'flow'                   => $this->suggestFlow($res),
                'status'                 => $this->mapStatus($res['status'] ?? null),

                // customer (use only if you have these inputs on the page)
                'customer_name'          => $res['c_driver_name'] ?? $res['c_name'] ?? null,
                'customer_email'         => $res['c_email'] ?? null,
                'customer_phone'         => $res['c_phone'] ?? null,
            ];

            return response()->json(['ok' => true, 'fields' => $fields, 'raw' => $res]);
        } catch (\Throwable $e) {
            throw ValidationException::withMessages([
                'ref_id' => "Import failed: {$e->getMessage()}",
            ]);
        }
    }

    private function suggestFlow(array $res): ?string
    {
        // Example: choose a flow based on VEVS payment method / status.
        $method = strtolower((string) ($res['payment_method'] ?? ''));
        if (str_contains($method, 'stripe')) return 'stripe-default';
        return null;
    }

    private function mapStatus(?string $vevsStatus): ?string
    {
        return match (strtolower((string) $vevsStatus)) {
            'completed', 'confirmed' => 'active',
            'pending'                => 'pending',
            'canceled', 'cancelled'  => 'cancelled',
            default                  => null,
        };
    }
}
