<?php

require_once 'vendor/autoload.php';
require_once 'secrets.php';

\Stripe\Stripe::setApiKey($stripeSecretKey);
header('Content-Type: application/json');

//$YOUR_DOMAIN = 'http://localhost:3000';

// Obtener el precio del formulario
//$precio = $_POST['precio'];

try{
    
if (!empty($_POST['donation']['amount'])) {
  $amount = $_POST['donation']['amount'];
  error_log(print_r($amount, TRUE)); 
  if (is_string($amount)) {
      $amount = intval($amount);
  }

  // Verifica si $amount es un número después de la conversión
  if (is_numeric($amount)) {
      // Realiza la operación
      $unitAmount = $amount * 100;
      
  } else {
      
  }
  if(strval($amount) == strval(3500.00)){
    $priceSubscription = 'price_1NTTlbBlb1fJ8sQqQV01BTah';
    $priceOneTime = 'price_1NTwNmBlb1fJ8sQqyFkVklkA';
  }else{
    $priceSubscription = 'price_1NTTlbBlb1fJ8sQqh1SL06te';
    $priceOneTime = 'price_1NUykTBlb1fJ8sQqRTscptPc';
  }

  $unitAmount = $amount * 100; // Convertir el precio a centavos (Stripe utiliza el precio en centavos)
} else {
  $unitAmount = 0; // Dejar el campo unit_amount vacío si no se proporciona un precio
}

$customerName = $_POST['donation']['first_name'];

if (!empty($_POST['donation']['last_name'])) {
  $customerName = $customerName.' '.$_POST['donation']['last_name'];
}

if(!empty($_POST['donation']['custom_values']['rfc'])){
  $rfc = urldecode($_POST['donation']['custom_values']['rfc']);
  $zip = $_POST['donation']['billing_address_attributes']['zip'];
  $satName = $_POST['donation']['custom_values']['razon_social'];
  $template = $templateCFDI;
}else{
  $rfc = $genericRFC;
  $zip = $genericCP;
  $satName = $genericSatName;
  $template = $templateCFDIGenerico;
}

if(!empty($_POST['donation']['custom_values']['direccion_fiscal'])){
  $customerAddress = urldecode($_POST['donation']['custom_values']['direccion_fiscal']);
}

if(!empty($_POST['regimenFiscal'])){
  $regimenFiscal = $_POST['regimenFiscal'];
}else{
  $regimenFiscal = $genericRegimen;
}
if(!empty($_POST['usoCfdi'])){
  $usoCfdi = $_POST['usoCfdi'];
}else{
  $usoCfdi = $genericUsoCfdi;
}


if(!empty($_POST['pageSlug'])){
  $pageSlug = $_POST['pageSlug'];
}else{
  $pageSlug = '';
}

// Verificar si se proporcionó un correo electrónico
if (!empty($_POST['donation']['email'])) {
  $correoElectronico = urldecode($_POST['donation']['email']);

  if (!filter_var($correoElectronico, FILTER_VALIDATE_EMAIL)) {
    if (preg_match('/"email"=>"([^"]+)"/', $correoElectronico, $matches)) {
      $correoElectronico = $matches[1];
      // Utilizar el valor obtenido
    }
  }

  error_log(print_r($correoElectronico, TRUE)); 
  // Almacenar el correo electrónico en la sesión
  $_SESSION['correoElectronico'] = $correoElectronico;

  // Configurar el campo de correo electrónico solo si está disponible
  //$clienteEmail = ['email' => $correoElectronico];
  $clienteEmail = $correoElectronico;
} else {
  // De lo contrario, no configurar el campo de correo electrónico
  $clienteEmail = [];
}
$stripe = new \Stripe\StripeClient($stripeSecretKey);

$firstName = $_POST['donation']['first_name'];
$lastName = $_POST['donation']['last_name'];
$isTest = $_POST['isTest'];
$isFlowNS = $_POST['flowNS'];



error_log(json_encode([
  $_POST
]));


$phone = $_POST['donation']['billing_address_attributes']['phone_number'];
$country = $_POST['donation']['billing_address_attributes']['country_code'];

$address1 = $_POST['donation']['billing_address_attributes']['address1'];
$address2 = $_POST['donation']['billing_address_attributes']['address2'];


$city = $_POST['donation']['billing_address_attributes']['city'];
$state = $_POST['donation']['billing_address_attributes']['state'];




$requireInvoice = $_POST['donation']['custom_values']['recibo'];

error_log("usoCfdi: ".$usoCfdi);
error_log("taxRegime: ".$regimenFiscal);
error_log("requireInvoice: ".$requireInvoice);


$currentDate = date("Y-m-d H:i:s");
//$isTest = true;


if(!empty($rfc)){
  if($rfc != $genericRFC){
    $searchCustomer = $stripe->customers->search([
      'query' => 'metadata["rfc"]:\''.$rfc.'\'',
    ]);
  }else{
    $searchCustomer = $stripe->customers->search([
      'query' => 'email:\''.$clienteEmail.'\'',
    ]);
  }
  
  $customerInfo = $searchCustomer->data;
}

if(empty($customerInfo)){
  $searchCustomer = $stripe->customers->search([
    'query' => 'email:\''.$clienteEmail.'\'',
  ]);
  $customerInfo = $searchCustomer->data;
}
if(empty($customerAddress)){
  $customerAddress = '';
}

if(!empty($customerInfo)){
    error_log("Existe cliente");
  $customer = $customerInfo[0]->id;
}else{
    error_log("Entra en crear cliente");

    
  $customerNew = $stripe->customers->create([
    'email' => $correoElectronico,
    'name' => $customerName,
    'address[line1]' => $address1,
    'address[line2]' => $address2,
    'address[city]' => $city,
    'address[state]' => $state,
    'address[postal_code]' => $zip,
    'address[country]' => $country,
    'metadata[rfc]' => $rfc
  ]);

  $customer = $customerNew;

  
}




$checkout_session = \Stripe\Checkout\Session::create([
    'line_items' => [[
      # Provide the exact Price ID (e.g. pr_1234) of the product you want to sell
      //'price' => $priceOneTime,
      'price_data' => [
        'currency' => 'MXN',
        'unit_amount' => $unitAmount, // Convertir el precio a centavos (Stripe utiliza el precio en centavos)
        'product_data' => [
          'name' => 'Donación única'
        ],
      ],
      'quantity' => 1
    ]],
    'mode' => 'payment',
    'payment_method_options' => [
      'card' => [
          'installments' => [
              'enabled' => true
          ],
          'setup_future_usage' => 'off_session'
      ]
    ],
    'metadata' => [
        'firstName'=> $firstName,
        'lastName'=> $lastName,
        "amount"=> $amount,
        "email"=> $correoElectronico,
        "phone"=> $phone,
        "country"=> $country,
        "address"=> $address1,
        "address2"=> $address2,
        "zip"=> $zip,
        "rfc"=> $rfc,
        "taxRegime"=> $regimenFiscal,
        "cfdiUse"=> $usoCfdi,
        "satName" => $satName,
        "city"=> $city,
        "state"=> $state,
        "isTest"=> filter_var($isTest, FILTER_VALIDATE_BOOLEAN),
        "flowNS"=> filter_var($isFlowNS, FILTER_VALIDATE_BOOLEAN),
        "templateCFDI" => $template,
        "pageSlug" => $pageSlug
    ],
    'customer' => $customer,
    //'customer_email' => $clienteEmail,
    'success_url' => 'https://auna.nationbuilder.com/confirmacion_donacion',
    'cancel_url' => 'https://auna.nationbuilder.com/prueba_donativos_msi',
  ]);

header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url);


  
}
catch (\Stripe\Exception\CardException $e){
  # "e" contains a message explaining why the request failed
  echo 'Card Error Message is:' . $e->getError()->message . '\n';
  echo json_encode([
      'error_message' => $e->getError()->message
  ]);
}
catch (\Stripe\Exception\InvalidRequestException $e) {
  // Invalid parameters were supplied to Stripe's API
  error_log(json_encode([
    $e->getError()
]));
  echo 'Invalid Parameters Message is:' . $e->getError()->message . '\n';
  
}