<?php

namespace Opentalent\OtCore\Domain\Repository;

use Opentalent\OtCore\Domain\Model\Donor;
use Opentalent\OtCore\Exception\ApiRequestException;

class DonorRepository extends BaseApiRepository
{
    const URI_TRAILING_PART = '/api/public/donors';
    const HYDRA_TYPE = 'PortailDonor';

    /**
     * Get the donors of the organization
     *
     * @param int $organizationId The id of the organization
     * @param int $page
     * @return ApiPagedCollection              Donors
     * @throws ApiRequestException
     */
    public function findByOrganizationId(int $organizationId, $page = 1) {
        $params = [];
        $params['organizationId'] = $organizationId;
        $params['page'] = $page;
        $params['itemsPerPage'] = 99;

        return $this->getApiRecords($params);
    }

    /**
     * Get the donors of the organization's parents
     *
     * @param int $organizationId The id of the organization
     * @param int $page
     * @return ApiPagedCollection              Donors
     * @throws ApiRequestException
     */
    public function findParentsByOrganizationId(int $organizationId, $page = 1) {
        $params = [];
        $params['organizationId'] = $organizationId;
        $params['parent'] = 1;
        $params['page'] = $page;
        $params['itemsPerPage'] = 99;

        return $this->getApiRecords($params);
    }

    /**
     * Returns a Donor object from an Api record
     *
     * @param $record
     * @return Donor|null
     */
    protected function memberToObject(array $record): ?Donor {
        if ($record['@type'] != $this::HYDRA_TYPE) {
            return null;
        }
        $donor = new Donor();
        $a = explode('/', $record['@id']);
        $donor->setId(end($a));
        $donor->setOrganizationId($record['organizationId']);
        $donor->setName($record['name']);
        $donor->setEmail($record['email']);
        $donor->setTelphone($record['telphone']);
        $donor->setWebsite($record['website']);
        $donor->setWording($record['wording']);
        $donor->setDisplayedOn($record['displayedOn']);
        $donor->setLogo($record['logo'] ?? null);

        return $donor;
    }
}
