<?php

namespace App\Repository;

use App\Entity\Payment;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpClient\HttpClient;

/**
 * @method Siege|null find($id, $lockMode = null, $lockVersion = null)
 * @method Siege|null findOneBy(array $criteria, array $orderBy = null)
 * @method Siege[]    findAll()
 * @method Siege[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class PaymentRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Payment::class);
    }

    /**
     * @param int $id User id
     *
     * @return Payment|null Returns user's last payment
     */
    public function getUserLastPayment($id)
    {
        $results = $this->findBy(
            ['clientId' => $id],
            ['id' => 'DESC'],
            1,
            0
        );

        if (empty($results)) {
            return null;
        } else {
            return $results[0];
        }
    }

    /*
     * Everytime a user clicks on "Payer en CB" button on the kohinos side,
     * a Payment entry is created, with status NULL.
     * We want to prevent a user from starting several payments, which can
     * lead to duplicates.
     * If we find a valid starting Payment, we will return the payzen URL used to start the payment.
     * We mark as unvalid Payment that are unvalid when we check them.
     */
    public function findUrlOfValidStartingPayment($clientEmail)
    {
        $candidates = $this->findBy([
            'clientEmail' => $clientEmail,
            'status' => null,
            'startingPaymentAnalysisStatus' => null,
        ]);

        foreach ($candidates as $p) {
            /* @var Payment $p */
            $url = $p->getPayzenStartingPaymentUrl();
            if (!$url) {
                $p->setStartingPaymentAnalysisStatus('NO URL');
                continue;
            }
            $createdAt = clone $p->getCreatedAt(); //don't modify original object
            $timeout = $createdAt->add(\DateInterval::createFromDateString("10 minutes"));
            if ($timeout < new \DateTime()) {
                $p->setStartingPaymentAnalysisStatus('TIMEOUT');
            } else {
                return $url;
            }
        }
        //no valid payment found
        return '';
    }
}
