<?php
// notify.php — endpoint para disparar notificação de status de pedido
// Uso: POST order_id=123&status=pago  (ou enviado/entregue/cancelado)

require_once __DIR__ . '/config.php';
header('Content-Type: application/json; charset=utf-8');

function jexit($ok, $msg, $extra = []) {
  http_response_code($ok ? 200 : 400);
  echo json_encode(array_merge(['success'=>$ok, 'message'=>$msg], $extra));
  exit;
}

try {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jexit(false, 'Método inválido. Use POST.');
  }

  $order_id = (int)($_POST['order_id'] ?? 0);
  $status   = trim($_POST['status'] ?? '');
  $permitidos = ['novo','pago','enviado','entregue','cancelado'];

  if ($order_id <= 0) jexit(false, 'order_id inválido.');
  if (!in_array($status, $permitidos, true)) jexit(false, 'status inválido.');

  // carrega pedido
  $st = $pdo->prepare("SELECT * FROM orders WHERE id=? LIMIT 1");
  $st->execute([$order_id]);
  $order = $st->fetch();
  if (!$order) jexit(false, 'Pedido não encontrado.');

  // escolhe template por status (site_config)
  $tplKey = [
    'pago'      => 'email_tpl_pago',
    'enviado'   => 'email_tpl_enviado',
    'entregue'  => 'email_tpl_entregue'
  ][$status] ?? null;

  $tpl = '';
  if ($tplKey) {
    $stc = $pdo->prepare("SELECT cfg_value FROM site_config WHERE cfg_key=? LIMIT 1");
    $stc->execute([$tplKey]);
    $tpl = (string)$stc->fetchColumn();
  }
  if ($tpl === '') {
    // fallback simples
    $tpl = "<p>Olá, {{NOME}}!<br>O seu pedido #{{PEDIDO}} foi atualizado para <strong>{{STATUS}}</strong>.<br>Total: R$ {{TOTAL}}</p>";
  }

  // substituições
  $html = strtr($tpl, [
    '{{NOME}}'   => $order['customer_name'] ?? '',
    '{{PEDIDO}}' => (string)$order['id'],
    '{{TOTAL}}'  => number_format((float)$order['total'], 2, ',', '.'),
    '{{STATUS}}' => strtoupper($status),
  ]);

  $sent = false; $resp = 'no-email';
  if (!empty($order['customer_email'])) {
    $to = $order['customer_email'];
    $subject = "Atualização do seu pedido #{$order['id']} - {$status}";
    if (function_exists('send_mail_smtp')) {
      $sent = send_mail_smtp($to, $subject, $html);
    } else {
      // fallback mínimo
      $headers  = "MIME-Version: 1.0\r\n";
      $headers .= "Content-type: text/html; charset=UTF-8\r\n";
      $headers .= "From: Charlotte Presentes <".(defined('FROM_EMAIL')?FROM_EMAIL:'no-reply@charlottepresentes.com.br').">\r\n";
      $sent = mail($to, $subject, $html, $headers);
    }
    $resp = $sent ? 'sent' : 'error';
  }

  // registra log
  try {
    $log = $pdo->prepare("INSERT INTO email_logs (order_id,to_email,subject,status_after,method,success,response)
                          VALUES (?,?,?,?,?,?,?)");
    $log->execute([
      $order['id'],
      $order['customer_email'] ?: null,
      "Atualização do pedido #{$order['id']} - {$status}",
      $status, $sent ? 'SMTP' : 'mail', $sent ? 1 : 0, $resp
    ]);
  } catch (Throwable $e) {
    // mantém silencioso
  }

  jexit(true, 'Notificação processada.', ['sent'=>$sent, 'status'=>$status]);

} catch (Throwable $e) {
  if (defined('DISPLAY_ERRORS') && DISPLAY_ERRORS) {
    jexit(false, 'Erro: '.$e->getMessage());
  }
  jexit(false, 'Erro interno.');
}
