<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Services\Support\ImageUploadService;

class AccountController extends BaseController
{
    /**
     * Personal profile photo — works for any logged-in role (candidate,
     * agency owner, recruiter), since profile_photo_path lives on `users`
     * itself, not a role-specific table. Distinct from
     * AgencyController::uploadLogo()/uploadCover(), which are the
     * company's own branding, not a person's headshot.
     */
    public function uploadPhoto()
    {
        $user = $this->currentUser();

        $file = $this->request->getFile('photo');
        if (! $file) {
            return $this->jsonError([['code' => 'FILE_MISSING', 'message' => 'No file uploaded under field "photo".']], 400);
        }

        try {
            $uploader = new ImageUploadService();
            $stored = $uploader->validateAndStore($file, 'photos');
        } catch (\InvalidArgumentException $e) {
            return $this->jsonError([['code' => 'INVALID_FILE', 'message' => $e->getMessage()]], 422);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'UPLOAD_FAILED', 'message' => $e->getMessage()]], 500);
        }

        $userModel = new UserModel();
        $existing = $userModel->find($user->id);
        (new ImageUploadService())->delete($existing->profile_photo_path); // clean up the old photo, no orphaned files

        $userModel->update($user->id, ['profile_photo_path' => $stored['relative_path']]);

        return $this->jsonSuccess(['photo_url' => base_url($stored['relative_path'])]);
    }

    public function removePhoto()
    {
        $user = $this->currentUser();
        $userModel = new UserModel();
        $existing = $userModel->find($user->id);

        (new ImageUploadService())->delete($existing->profile_photo_path);
        $userModel->update($user->id, ['profile_photo_path' => null]);

        return $this->jsonSuccess(['message' => 'Profile photo removed.']);
    }
}
