<?php
namespace App\Service\Billing;
use App\Entity\Payment\Subscription;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManagerInterface;
use DateTime;
use App\Entity\Centre;
use App\Entity\Factures;
use App\Entity\Plan;
use App\Entity\PaymentMethod;
use App\Entity\Audio;
use Doctrine\Persistence\ManagerRegistry;
const URL_CLIENT_BILLING_ATOL = "https://myaudio.vosfactures.fr/clients.json";
const URL_INVOICE_BILLING_ATOL = "https://myaudio.vosfactures.fr/invoices.json";
class BillingAtolService
{
private $entityManager;
private $publicFunction;
private $apiTokenBilling;
private $productIdMap = [
'yearly' => '17325102572', // Annual subscription price ID : Abonnement My Audio Pro Atol annuel pendant 12 mois (900€/an)
];
public function __construct(EntityManagerInterface $entityManager,string $apiTokenBilling)
{
$this->entityManager = $entityManager;
$this->apiToken = $apiTokenBilling;
}
public function createClient(Centre $centre, array $data)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => URL_CLIENT_BILLING_ATOL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"api_token": "'.$this->apiToken.'",
"client": {
"name":"'.$centre->getName().'",
"city": "'.$centre->getCity().'",
"country": "France",
"email": "'.$centre->getIdGerant()->getMail().'",
"post_code": "'.$centre->getPostale().'",
"street":"'.$centre->getAddress().'",
"phone": "'.$centre->getPhone().'"
}
}',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json'
),
));
$response1 = curl_exec($curl);
$rep = json_decode($response1);
//dd($data);
$factureId = $rep->{'id'};
$centre->setFactureId($rep->{'id'});
$this->entityManager->flush();
if($data['plan'] == "Multi-Audios")
{
$additionalProductId = $data['period'] == "month" ?
$this->productIdMap['monthly'] :
$this->productIdMap['yearly'];
$productData = [
[
"product_id" => $additionalProductId,
"quantity" => 1,
]
];
}
else {
$additionalProductId = $data['period'] == "month" ?
$this->productIdMap['monthly'] :
$this->productIdMap['yearly'];
$productData = [
[
"product_id" => $additionalProductId,
"quantity" => 1,
]
];
}
// dd($productData);
$this->createBilling($centre,intval($centre->getFactureId()),$productData);
}
// for special new annual billing from 900 to 1000
public function createClientUpdatedYearly(Centre $centre, array $data)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => URL_CLIENT_BILLING_ATOL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"api_token": "'.$this->apiToken.'",
"client": {
"name":"'.$centre->getName().'",
"city": "'.$centre->getCity().'",
"country": "France",
"email": "'.$centre->getIdGerant()->getMail().'",
"post_code": "'.$centre->getPostale().'",
"street":"'.$centre->getAddress().'",
"phone": "'.$centre->getPhone().'"
}
}',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json'
),
));
$response1 = curl_exec($curl);
$rep = json_decode($response1);
//dd($data);
$factureId = $rep->{'id'};
$centre->setFactureId($rep->{'id'});
$this->entityManager->flush();
if($data['plan'] == "Multi-Audios")
{
$additionalProductId = $this->productIdMap['nextYearYearly'] ;
$productData = [
[
"product_id" => $additionalProductId,
"quantity" => 1,
]
];
if ($data['quantity'] > 1) {
$additionalProductId = $this->productIdMap['additionalAudioYearly'];
$quantity = $data['quantity'] - 1;
$additionalProduct = [
"product_id" => $additionalProductId,
"quantity" => $quantity,
];
$productData = array_merge($productData, [$additionalProduct]);
}
}
else {
$additionalProductId = $this->productIdMap['nextYearYearly'] ;
$productData = [
[
"product_id" => $additionalProductId,
"quantity" => 1,
]
];
if ($data['quantity'] > 1) {
$additionalProductId = $this->productIdMap['additionnalCenterYearly'];
$quantity = $data['quantity'] - 1;
$additionalProduct = [
"product_id" => $additionalProductId,
"quantity" => $quantity,
];
$productData = array_merge($productData, [$additionalProduct]);
}
}
// dd($productData);
$this->createBilling($centre,intval($centre->getFactureId()),$productData);
}
function createInvoicePayload($apiTokenBilling, $departmentId, $clientId, $productData) {
$positions = [];
foreach ($productData as $product) {
$position = [
"product_id" => $product['product_id'],
"quantity" => $product['quantity']
];
if (isset($product['discount'])) {
$position["discount"] = $product['discount'];
}
$positions[] = $position;
}
// dd($positions);
$payload = [
"api_token" => $apiTokenBilling,
"invoice" => [
"department_id" => $departmentId,
"client_id" => $clientId,
"test" => false,
"discount_kind" => "amount",
"show_discount" => false,
"positions" => $positions,
]
];
return json_encode($payload);
}
public function createBilling(Centre $center,int $client, array $data)
{
$apiTokenBilling = $this->apiToken;
//$departmentId = $data['departmentId'];
$departmentId = 937362;
$clientId = $client;
/*$productData = [
["product_id" => 102520343, "quantity" => 1, "discount" => $reduction],
];*/
$productData = $data;
$payload = $this->createInvoicePayload($apiTokenBilling, $departmentId, $clientId, $productData);
// cURL setup
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => URL_INVOICE_BILLING_ATOL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json'
),
));
$fact = curl_exec($curl);
$fact = json_decode($fact);
$target = new DateTime('now');
// dd($fact);
$factId = $fact->{'id'};
$tokenId = $fact->{'token'};
$numeroFact = $fact->{'number'};
$montantHT = $fact->{'price_net'};
$montantTTC = $fact->{'price_gross'};
$dateFact = $target;
//POST FACTURE
$facture = new Factures();
$facture->setId(intval($factId));
$facture->setToken($tokenId);
$facture->setDate($dateFact);
$facture->setCentre($center);
$facture->setNumero($numeroFact);
$facture->setPrixHT($montantHT);
$facture->setPrixTTC($montantTTC);
$this->entityManager->persist($facture);
$this->entityManager->flush();
// save the billing
$this->downloadInvoice($facture);
return [
"message" => "Facture create succesefully",
"status" => 200,
];
}
public function downloadInvoice(Factures $invoice)
{
// cURL setup
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://myaudio.vosfactures.fr/invoices/".$invoice->getId().".pdf?api_token=".$this->apiToken,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTPGET => true
));
$response = curl_exec($curl);
if (curl_errno($curl)) {
echo 'cURL error: ' . curl_error($curl);
}
curl_close($curl);
/*$filename = str_replace('/', '-', $invoice->getNumero());
$outputPath = 'assets/partner/facture' . $filename . '.pdf';*/
// Your specified output path
$outputPath = 'assets/partner/facture' . $invoice->getToken() . '.pdf';
// Check if the directory exists, if not create it
if (!file_exists(dirname($outputPath))) {
mkdir(dirname($outputPath), 0755, true);
}
// Save the PDF file
file_put_contents($outputPath, $response);
}
}