<?php
/**
 * Tom's Java Jive - Square Webhook Handler
 */

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/square.php';
require_once __DIR__ . '/../includes/loyalty.php';
require_once __DIR__ . '/../includes/email.php';

header('Content-Type: application/json');

$payload   = file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_X_SQUARE_HMACSHA256_SIGNATURE'] ?? '';
$notificationUrl = SITE_URL . '/api/webhook.php';

if (empty(SQUARE_WEBHOOK_SIGNATURE_KEY) || SQUARE_WEBHOOK_SIGNATURE_KEY === 'REPLACE_ME') {
    error_log('Square webhook signature key not configured - rejecting webhook');
    http_response_code(400);
    exit();
}

if (!verifySquareWebhookSignature($payload, $sigHeader, $notificationUrl, SQUARE_WEBHOOK_SIGNATURE_KEY)) {
    error_log('Square webhook signature verification failed');
    http_response_code(400);
    exit();
}

$event = json_decode($payload, true);
if (!$event) {
    http_response_code(400);
    exit();
}

$eventType = $event['type'] ?? '';

switch ($eventType) {

    case 'payment.updated':
    case 'payment.created':
        $payment   = $event['data']['object']['payment'] ?? [];
        $paymentId = $payment['id'] ?? '';
        $status    = $payment['status'] ?? '';
        $orderId   = $payment['reference_id'] ?? null;
        if ($paymentId && $status) {
            markSquarePaymentResult($paymentId, $orderId, $status);
        }
        break;

    case 'refund.updated':
    case 'refund.created':
        $refund    = $event['data']['object']['refund'] ?? [];
        $paymentId = $refund['payment_id'] ?? '';
        $status    = $refund['status'] ?? '';
        if ($status === 'COMPLETED' && $paymentId) {
            db()->update('orders',
                [
                    'payment_status' => 'refunded',
                    'order_status'   => 'refunded',
                ],
                'square_payment_id = :pid',
                ['pid' => $paymentId]
            );
        }
        break;
}

http_response_code(200);
echo json_encode(['received' => true]);
