<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Profile\ChangePasswordRequest;
use App\Http\Requests\Profile\UpdateMedicalRequest;
use App\Http\Requests\Profile\UpdateProfileRequest;
use App\Http\Requests\Profile\UploadPhotoRequest;
use App\Http\Resources\UserMedicalDetailResource;
use App\Http\Resources\UserResource;
use App\Models\UserMedicalDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Laravel\Facades\Image;

class ProfileController extends Controller
{
    public function show(Request $request)
    {
        $user = $request->user()->load('medicalDetail', 'attachments');

        return $this->success(new UserResource($user));
    }

    public function update(UpdateProfileRequest $request)
    {
        $request->user()->update($request->validated());

        return $this->success(
            new UserResource($request->user()->fresh()->load('medicalDetail')),
            'Profile updated.'
        );
    }

    public function uploadPhoto(UploadPhotoRequest $request)
    {
        $user = $request->user();

        // Delete old photo if exists
        if ($user->profile_photo) {
            Storage::disk('public')->delete($user->profile_photo);
        }

        // Resize to max 800×800 (maintaining aspect ratio) and encode as JPEG
        $encoded = Image::read($request->file('photo'))
            ->scaleDown(width: 800, height: 800)
            ->toJpeg(quality: 85);

        $filename = 'profile-photos/' . $user->id . '_' . time() . '.jpg';
        Storage::disk('public')->put($filename, $encoded->toString());

        $user->update(['profile_photo' => $filename]);

        return $this->success(
            new UserResource($user->fresh()->load('medicalDetail')),
            'Profile photo updated.'
        );
    }

    public function showMedical(Request $request)
    {
        $medical = $request->user()->medicalDetail;

        return $this->success(
            $medical ? new UserMedicalDetailResource($medical) : null
        );
    }

    public function updateMedical(UpdateMedicalRequest $request)
    {
        $medical = UserMedicalDetail::updateOrCreate(
            ['user_id' => $request->user()->id],
            $request->validated()
        );

        return $this->success(
            new UserMedicalDetailResource($medical),
            'Medical details updated.'
        );
    }

    public function updateFcmToken(Request $request)
    {
        $request->validate([
            'fcm_token' => ['required', 'string', 'max:255'],
        ]);

        $request->user()->update(['fcm_token' => $request->fcm_token]);

        return $this->success(null, 'FCM token updated.');
    }

    public function changePassword(ChangePasswordRequest $request)
    {
        $user = $request->user();

        if (! Hash::check($request->current_password, $user->password)) {
            return $this->error('Current password is incorrect.', 422);
        }

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

        // Revoke all other tokens so other devices must re-login
        $user->tokens()->where('id', '!=', $user->currentAccessToken()->id)->delete();

        return $this->success(null, 'Password changed successfully.');
    }
}
