<?php
/**
 * Cancel pending order when store owner confirms customer didn't make payment
 * - Marks order as 'failed'
 * - Updates status_updated_at timestamp
 */

session_start();
require_once 'config.php';
require_once 'app/classes/StoreManager.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$userId = $_SESSION['user_id'];
$orderId = intval($_POST['order_id'] ?? 0);

if ($orderId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
    exit;
}

// Verify user owns a store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    echo json_encode(['success' => false, 'message' => 'Store not found']);
    exit;
}

// Get order details and verify it belongs to the store and is pending
$orderStmt = $conn->prepare("
    SELECT 
        o.id,
        o.order_reference,
        o.store_id,
        o.status
    FROM orders o
    WHERE o.id = ? AND o.store_id = ? AND o.status = 'pending'
");
$orderStmt->bind_param("ii", $orderId, $store['id']);
$orderStmt->execute();
$orderResult = $orderStmt->get_result();
$order = $orderResult->fetch_assoc();
$orderStmt->close();

if (!$order) {
    echo json_encode(['success' => false, 'message' => 'Order not found, already processed, or does not belong to your store']);
    exit;
}

// Update order status to 'failed'
$updateStmt = $conn->prepare("
    UPDATE orders 
    SET status = 'failed',
        status_updated_at = NOW() 
    WHERE id = ?
");
$updateStmt->bind_param("i", $orderId);

if ($updateStmt->execute()) {
    $updateStmt->close();
    
    echo json_encode([
        'success' => true,
        'message' => 'Order cancelled successfully',
        'order_id' => $orderId,
        'order_reference' => $order['order_reference'] ?? null
    ]);
} else {
    $updateStmt->close();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to cancel order: ' . $conn->error
    ]);
}
?>






















