<?php

namespace App\Http\Controllers\Api\Driver;

use App\Http\Controllers\Controller;
use App\Models\Driver;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

class ProfileController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver, 404, __('api.no_driver_profile'));

        return response()->json([
            'user' => $request->user()->only(['id', 'name', 'email', 'phone']),
            'driver' => $driver->load('documents'),
            'documents_status' => $this->documentsStatus($driver),
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $user = $request->user();

        $data = $request->validate([
            'name' => ['sometimes', 'string', 'max:255'],
            'phone' => ['sometimes', 'nullable', 'string', 'max:50'],
            'email' => ['sometimes', 'email', Rule::unique('users', 'email')->ignore($user->id)],
        ]);

        $user->update($data);

        return response()->json(['user' => $user->only(['id', 'name', 'email', 'phone'])]);
    }

    public function changePassword(Request $request): JsonResponse
    {
        $data = $request->validate([
            'current_password' => ['required', 'string'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $user = $request->user();

        if (! Hash::check($data['current_password'], $user->password)) {
            throw ValidationException::withMessages(['current_password' => 'Current password is incorrect.']);
        }

        $user->update(['password' => $data['password']]);

        return response()->json(['message' => __('api.password_updated')]);
    }

    /**
     * Per-document expiry/approval flags for the driver's home screen —
     * mirrors the old project's getuserprofile document-status summary.
     */
    private function documentsStatus(Driver $driver): array
    {
        return $driver->documents->map(fn ($doc) => [
            'type' => $doc->type,
            'status' => $doc->status,
            'expiry_date' => $doc->expiry_date?->toDateString(),
            'is_expired' => $doc->isExpired(),
        ])->all();
    }
}
