<?php
// ============================================================
//  INTEGRAÇÃO UTMIFY (webhook estilo Shopify)
//  Envia o pedido como "pending" ao gerar o Pix e como "paid"
//  quando o pagamento é confirmado.
// ============================================================

if (!defined('UTMIFY_WEBHOOK_URL')) {
  define('UTMIFY_WEBHOOK_URL', 'https://api.utmify.com.br/webhooks/shopify?id=6a6f36651b84a359459692c5');
}

// Onde guardamos o pedido entre a criação do Pix e a confirmação
function utmify_store_dir() {
  $dir = __DIR__ . '/storage/orders';
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
  return $dir;
}

function utmify_store_path($id) {
  return utmify_store_dir() . '/' . preg_replace('/[^\w-]/', '', (string)$id) . '.json';
}

function utmify_save_order($id, array $order) {
  $path = utmify_store_path($id);
  @file_put_contents($path, json_encode($order), LOCK_EX);
}

function utmify_load_order($id) {
  $path = utmify_store_path($id);
  if (!is_file($path)) return null;
  $data = json_decode((string)@file_get_contents($path), true);
  return is_array($data) ? $data : null;
}

// Evita enviar o mesmo status duas vezes (status.php roda em polling)
function utmify_already_sent($id, $status) {
  $order = utmify_load_order($id);
  return $order && !empty($order['sent'][$status]);
}

function utmify_mark_sent($id, $status) {
  $order = utmify_load_order($id);
  if (!$order) return;
  if (!isset($order['sent']) || !is_array($order['sent'])) $order['sent'] = [];
  $order['sent'][$status] = time();
  utmify_save_order($id, $order);
}

function utmify_money($cents) {
  return number_format(((int)$cents) / 100, 2, '.', '');
}

function utmify_note_attributes(array $tracking) {
  $out = [];
  foreach ($tracking as $k => $v) {
    if ($v === null || $v === '' || is_array($v)) continue;
    $out[] = ['name' => (string)$k, 'value' => (string)$v];
  }
  return $out;
}

function utmify_landing_site(array $tracking) {
  $qs = [];
  foreach (['utm_source','utm_medium','utm_campaign','utm_content','utm_term','fbclid','gclid','src','sck'] as $k) {
    if (!empty($tracking[$k])) $qs[$k] = $tracking[$k];
  }
  return '/' . ($qs ? '?' . http_build_query($qs) : '');
}

/**
 * Monta o payload no formato de pedido Shopify (aceito pelo webhook da Utmify)
 * e envia. $financialStatus: 'pending' | 'paid' | 'refunded' | 'voided'
 */
function utmify_send(array $order, $financialStatus) {
  $tracking = isset($order['tracking']) && is_array($order['tracking']) ? $order['tracking'] : [];
  $nameParts = preg_split('/\s+/', trim((string)$order['name']));
  $firstName = $nameParts[0] ?? '';
  $lastName  = count($nameParts) > 1 ? end($nameParts) : '';

  $createdAt = isset($order['created_at']) ? $order['created_at'] : gmdate('c');
  $bump      = (int)($order['bump_cents'] ?? 0);
  $total     = (int)($order['amount_cents'] ?? 0);
  // O frete entra como parte do valor do produto (subtotal), e não mais
  // como "shipping" separado. Motivo: a Utmify usa o subtotal_price (valor
  // de produto) como "valor da venda" em vários painéis/relatórios, e não
  // soma o shipping_lines a isso. Como o kit é grátis e o frete é, na
  // prática, o valor real cobrado do cliente, ele precisa contar como
  // receita — por isso reportamos "shipping" como 0 e deixamos o valor
  // inteiro (kit + frete + bump) dentro do subtotal/line_items.
  $subtotal  = $total; // kit + frete + order bump
  $kitCents  = max(0, $subtotal - $bump); // kit + frete
  $shippingReported = 0;

  $address = [
    'first_name'  => $firstName,
    'last_name'   => $lastName,
    'address1'    => (string)($order['address'] ?? ''),
    'address2'    => (string)($order['neighborhood'] ?? ''),
    'city'        => (string)($order['city'] ?? ''),
    'province'    => (string)($order['state'] ?? ''),
    'province_code' => (string)($order['state'] ?? ''),
    'zip'         => (string)($order['zip'] ?? ''),
    'country'     => 'Brazil',
    'country_code'=> 'BR',
    'phone'       => (string)($order['phone'] ?? ''),
  ];

  $payload = [
    'id'               => (string)$order['id'],
    'order_number'     => (string)$order['id'],
    'name'             => '#' . substr((string)$order['id'], -8),
    'token'            => (string)$order['id'],
    'checkout_id'      => (string)$order['id'],
    'checkout_token'   => (string)$order['id'],
    'email'            => (string)($order['email'] ?? ''),
    'phone'            => (string)($order['phone'] ?? ''),
    'currency'         => 'BRL',
    'presentment_currency' => 'BRL',
    'created_at'       => $createdAt,
    'updated_at'       => gmdate('c'),
    'processed_at'     => $createdAt,
    'financial_status' => $financialStatus,
    'fulfillment_status' => null,
    'gateway'          => 'pix',
    'payment_gateway_names' => ['pix'],
    'test'             => false,
    'total_price'      => utmify_money($total),
    'subtotal_price'   => utmify_money($subtotal),
    'total_tax'        => '0.00',
    'total_discounts'  => '0.00',
    'total_shipping_price_set' => [
      'shop_money' => ['amount' => utmify_money($shippingReported), 'currency_code' => 'BRL'],
    ],
    'shipping_lines'   => [[
      'title' => (string)($order['shipping_label'] ?? 'Frete'),
      'price' => utmify_money($shippingReported),
    ]],
    'line_items'       => array_values(array_filter([
      [
        'id'         => 'kit-' . (string)($order['kit'] ?? ''),
        'product_id' => 'kit-' . (string)($order['kit'] ?? ''),
        'sku'        => 'kit-' . (string)($order['kit'] ?? ''),
        'title'      => (string)($order['kit_title'] ?? 'Kit Body Splash wepink'),
        'name'       => (string)($order['kit_title'] ?? 'Kit Body Splash wepink'),
        'quantity'   => 1,
        'price'      => utmify_money($kitCents),
        'requires_shipping' => true,
      ],
      $bump > 0 ? [
        'id'         => 'orderbump-' . (string)($order['kit'] ?? ''),
        'product_id' => 'orderbump-' . (string)($order['kit'] ?? ''),
        'sku'        => 'orderbump-' . (string)($order['kit'] ?? ''),
        'title'      => (string)($order['bump_title'] ?? 'Mais um Kit 5 Body Splash'),
        'name'       => (string)($order['bump_title'] ?? 'Mais um Kit 5 Body Splash'),
        'quantity'   => 1,
        'price'      => utmify_money($bump),
        'requires_shipping' => true,
      ] : null,
    ])),
    'customer' => [
      'id'         => (string)($order['email'] ?? ''),
      'email'      => (string)($order['email'] ?? ''),
      'first_name' => $firstName,
      'last_name'  => $lastName,
      'phone'      => (string)($order['phone'] ?? ''),
      'default_address' => $address,
    ],
    'billing_address'  => $address,
    'shipping_address' => $address,
    'landing_site'     => utmify_landing_site($tracking),
    'referring_site'   => (string)($tracking['referrer'] ?? ''),
    'note_attributes'  => utmify_note_attributes($tracking),
    'browser_ip'       => (string)($order['ip'] ?? ''),
    'client_details'   => [
      'browser_ip' => (string)($order['ip'] ?? ''),
      'user_agent' => (string)($order['user_agent'] ?? ''),
    ],
    'cancelled_at'     => null,
  ];

  if ($financialStatus === 'paid') {
    $payload['closed_at'] = gmdate('c');
    $payload['confirmed'] = true;
  }

  $ch = curl_init(UTMIFY_WEBHOOK_URL);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_HTTPHEADER     => [
      'Content-Type: application/json',
      'Accept: application/json',
      'X-Shopify-Topic: ' . ($financialStatus === 'paid' ? 'orders/paid' : 'orders/create'),
      'X-Shopify-Shop-Domain: gummyhair.checkout',
    ],
  ]);
  $body   = curl_exec($ch);
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($status < 200 || $status >= 300) {
    error_log('Utmify webhook falhou [' . $status . '] (' . $financialStatus . '): ' . $body);
    return false;
  }
  return true;
}

/** Envia um status apenas uma vez por pedido. */
function utmify_notify($id, $financialStatus) {
  if (utmify_already_sent($id, $financialStatus)) return true;
  $order = utmify_load_order($id);
  if (!$order) return false;
  $ok = utmify_send($order, $financialStatus);
  if ($ok) utmify_mark_sent($id, $financialStatus);
  return $ok;
}