80 lines
2.6 KiB
PHP
80 lines
2.6 KiB
PHP
<?php
|
|
/**
|
|
* Orders Action - Create orders via WooCommerce
|
|
*/
|
|
|
|
/**
|
|
* Handle create_order action
|
|
*
|
|
* @return void
|
|
*/
|
|
function handleCreateOrder(): void
|
|
{
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
try {
|
|
$woocommerce = getWooCommerce();
|
|
$db = getDatabase();
|
|
|
|
$email = $input['billing']['email'];
|
|
$mediacode = $input['mediacode_internal'] ?? 'Geen';
|
|
|
|
$input['payment_method'] = 'cod';
|
|
$input['payment_method_title'] = 'Sales Panel Order';
|
|
$input['status'] = 'on-hold';
|
|
|
|
// Check for existing customer
|
|
$existing = $woocommerce->get('customers', ['email' => $email]);
|
|
$input['customer_id'] = !empty($existing) ? $existing[0]->id : 0;
|
|
|
|
// Handle shipping costs
|
|
$shipping_incl = (float)($input['shipping_total'] ?? 0);
|
|
if ($shipping_incl > 0) {
|
|
$input['shipping_lines'] = [[
|
|
'method_id' => 'flat_rate',
|
|
'method_title' => 'Verzendkosten',
|
|
'total' => number_format($shipping_incl / 1.21, 4, '.', '')
|
|
]];
|
|
}
|
|
|
|
// Add customer note with agent info
|
|
$input['customer_note'] = "Agent: {$_SESSION['user']} | Mediacode: $mediacode";
|
|
|
|
// Add attribution metadata
|
|
$input['meta_data'][] = ['key' => '_wc_order_attribution_source_type', 'value' => 'utm'];
|
|
$input['meta_data'][] = ['key' => '_wc_order_attribution_utm_source', 'value' => 'SalesPanel'];
|
|
$input['meta_data'][] = ['key' => '_wc_order_attribution_utm_campaign', 'value' => $mediacode];
|
|
$input['meta_data'][] = ['key' => 'Mediacode', 'value' => $mediacode];
|
|
$input['meta_data'][] = ['key' => 'Bron', 'value' => 'SalesPanel'];
|
|
|
|
// Create the order
|
|
$order = $woocommerce->post('orders', $input);
|
|
|
|
// Log the order
|
|
$action_type = 'order_created';
|
|
$log_stmt = $db->prepare(
|
|
"INSERT INTO sales_logs (username, action_type, order_id, amount, mediacode, customer_email, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, NOW())"
|
|
);
|
|
$log_stmt->bind_param(
|
|
"ssidss",
|
|
$_SESSION['user'],
|
|
$action_type,
|
|
$order->id,
|
|
$order->total,
|
|
$mediacode,
|
|
$email
|
|
);
|
|
$log_stmt->execute();
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'order_id' => $order->id,
|
|
'total' => $order->total
|
|
]);
|
|
} catch (Exception $e) {
|
|
http_response_code(422);
|
|
echo json_encode(['error' => $e->getMessage()]);
|
|
}
|
|
}
|