<?php

namespace App\Repository;

use App\Entity\Payment;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Payum\Core\Request\GetHumanStatus;
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.
     * We want to prevent a user from starting several payments, which can
     * lead to duplicates.
     * We mark as unvalid Payment that are unvalid when we check them.
     */
    public function findValidStartingPayment($clientEmail)
    {
        //Remark : we don't know how to redirect the user to the existing payment page,
        //we simply return the datetime when the payment will be expired.
        $candidates = $this->findBy([
            'clientEmail' => $clientEmail,
            'startingPaymentAnalysisStatus' => null,
        ]);

        foreach ($candidates as $p) {
            if (!in_array($p->getStatus(),[null,GetHumanStatus::STATUS_NEW])) {
                $p->setStartingPaymentAnalysisStatus('NOT CONCERNED');
                continue;
            }
            if (!$p->getCreatedAt()) {
                $p->setStartingPaymentAnalysisStatus('TIMEOUT');
            } else {
                $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 $timeout;
                }
            }
        }
        //Note : some fields updates are done in this method to exclude non-candidate payment from future research.
        //We may not want to flush here so flushing will probably not occur when an ongoing starting payment is found,
        //but it will occur only when the payment process succeeds, which is fine.

        //no valid payment found
        return null;
    }
}
