<?php
/**
 * Tom's Java Jive - Check Payment Status API
 * Reconciliation-only fallback: Square payments complete synchronously in
 * create-square-payment.php, so this endpoint only matters if the browser
 * lost that response after Square had already accepted the charge. It shares
 * markSquarePaymentResult() with the webhook and the synchronous path so
 * loyalty points/emails are never duplicated no matter which path resolves first.
 */

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');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

$orderId = $_GET['order_id'] ?? '';

if (empty($orderId)) {
    jsonResponse(['error' => 'Order ID required'], 400);
}

$order = db()->fetch(
    "SELECT * FROM orders WHERE order_id = :id",
    ['id' => $orderId]
);

if (!$order) {
    jsonResponse(['error' => 'Order not found'], 404);
}

if ($order['payment_status'] === 'paid') {
    jsonResponse([
        'status'         => 'complete',
        'payment_status' => 'paid',
        'order_id'       => $order['order_id'],
        'order_number'   => $order['order_number'],
        'redirect'       => '/order-confirmation.php?order=' . $order['order_id']
    ]);
}

if (!isSquareConfigured()) {
    jsonResponse([
        'status'         => 'demo_mode',
        'payment_status' => $order['payment_status'],
        'message'        => 'Square not configured - running in demo mode'
    ]);
}

if (empty($order['square_payment_id'])) {
    jsonResponse([
        'status'         => 'pending',
        'payment_status' => $order['payment_status']
    ]);
}

try {
    $result  = squareGetPayment($order['square_payment_id']);
    $payment = $result['payment'] ?? [];
    $status  = $payment['status'] ?? '';

    markSquarePaymentResult($order['square_payment_id'], $order['order_id'], $status);

    $updated = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $order['order_id']]);

    if ($updated['payment_status'] === 'paid') {
        jsonResponse([
            'status'         => 'complete',
            'payment_status' => 'paid',
            'order_id'       => $updated['order_id'],
            'order_number'   => $updated['order_number'],
            'redirect'       => '/order-confirmation.php?order=' . $updated['order_id']
        ]);
    }

    jsonResponse([
        'status'         => $status,
        'payment_status' => $updated['payment_status']
    ]);

} catch (Exception $e) {
    error_log('Square payment status check error: ' . $e->getMessage());
    jsonResponse([
        'status'         => 'error',
        'payment_status' => $order['payment_status'],
        'error'          => 'Failed to check payment status'
    ]);
}
