<?php
// FILE: api/admin/manage_order.php
// --- SETUP ---
ini_set('display_errors', 1);
error_reporting(E_ALL);
header("Content-Type: application/json; charset=UTF-8");

require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

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

// --- ROUTING ---
try {
    if ($method === 'GET') {
        if (empty($orderId) && empty($token)) {
            throw new Exception("Order ID or token is required.", 400);
        }
        handleGetRequest($db, $orderId, $token);
    } elseif ($method === 'PUT') {
        $input = json_decode(file_get_contents('php://input'), true);
        $orderId = $input['order_id'] ?? $orderId;
        $token = $input['token'] ?? $token;

        if (empty($orderId) && empty($token)) {
            throw new Exception("Order ID or token is required.", 400);
        }
        handlePutRequest($db, $orderId, $token, $input);
    } else {
        throw new Exception("Method not allowed.", 405);
    }
} catch (Exception $e) {
    $statusCode = $e->getCode() >= 400 ? $e->getCode() : 500;
    http_response_code($statusCode);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

// --- FUNCTIONS ---
function handleGetRequest($db, $orderId, $token) {
    if ($orderId) {
        $stmt = $db->prepare("SELECT id, status, payment_status, total_price, payment_method FROM orders WHERE id = ?");
        $stmt->bind_param('s', $orderId);
    } else {
        $stmt = $db->prepare("SELECT id, status, payment_status, total_price, payment_method FROM orders WHERE payment_confirmation_token = ?");
        $stmt->bind_param('s', $token);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    $order = $result->fetch_assoc();
    $stmt->close();

    if (!$order) {
        throw new Exception("Order not found.", 404);
    }
    echo json_encode(['success' => true, 'data' => $order]);
}

function handlePutRequest($db, $orderId, $token, $input) {
    $action = $input['action'] ?? null;
    if (!$action) {
        throw new Exception("An 'action' is required in the request body.", 400);
    }

    $sql = '';
    $message = '';
    $params = [];
    $types = '';

    switch ($action) {
        case 'mark_delivered':
            $sql = "UPDATE orders SET status = 'delivered', payment_status = IF(payment_method = 'cash_on_delivery', 'paid', payment_status) WHERE ";
            $message = "Order marked as Delivered.";
            break;
        case 'cancel_order':
            $sql = "UPDATE orders SET status = 'cancelled' WHERE ";
            $message = "Order cancelled successfully.";
            break;
        default:
            throw new Exception("Invalid action.", 400);
    }
    
    if ($orderId) {
        $sql .= "id = ?";
        $params[] = $orderId;
        $types .= 's';
    } else {
        $sql .= "payment_confirmation_token = ?";
        $params[] = $token;
        $types .= 's';
    }

    $stmt = $db->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    
    if ($stmt->affected_rows > 0) {
        echo json_encode(['success' => true, 'message' => $message]);
    } else {
        throw new Exception("Order not found or no update was needed.", 404);
    }
    $stmt->close();
}
?>