<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
    exit;
}

try {
    $conn->begin_transaction();
    
    // Generate unique order number
    $order_number = 'HOLD-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // Check if order number already exists
    $check_stmt = $conn->prepare("SELECT id FROM held_orders WHERE order_number = ?");
    $check_stmt->bind_param("s", $order_number);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows > 0) {
        // Generate a new number if collision
        $order_number = 'HOLD-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }
    $check_stmt->close();
    
    // Handle customer information
    $customer_id = null;
    $customer_name = $input['customer_name'] ?? null;
    $customer_phone = $input['customer_phone'] ?? null;
    $table_number = $input['table_number'] ?? null;
    $notes = $input['notes'] ?? null;
    
    if (!empty($input['customer_id'])) {
        $customer_id = intval($input['customer_id']);
    }
    
    if ($customer_phone && trim($customer_phone) !== '') {
        $customer_phone = trim($customer_phone);
        
        // Create customer with name if provided, otherwise use blank
        $name_for_customer = !empty($customer_name) ? trim($customer_name) : '';
        $stmt = $conn->prepare("INSERT IGNORE INTO customers (name, phone, created_at) VALUES (?, ?, NOW())");
        $stmt->bind_param("ss", $name_for_customer, $customer_phone);
        $stmt->execute();
        
        // Get customer ID
        $stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
        $stmt->bind_param("s", $customer_phone);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        if ($result) {
            $customer_id = $result['id'];
        }
        $stmt->close();
    }
    
    // Calculate totals
    $subtotal = 0;
    foreach ($input['items'] as $item) {
        $subtotal += floatval($item['total']);
    }
    
    $discount = floatval($input['discount'] ?? 0);
    $discount_amount = $subtotal * ($discount / 100);
    $total_amount = $subtotal - $discount_amount;
    
    // Store order data as JSON
    $order_data = json_encode($input);
    
    // Get current user (if you have user authentication)
    $created_by = 'POS_USER'; // You can modify this if you have user sessions
    
    // Insert held order (temporarily without customer_name and table_number until database is updated)
    // For now, we'll store customer_name, table_number, and notes in the order_data JSON
    $order_data_with_details = json_encode([
        'items' => $input['items'],
        'customer_name' => $customer_name,
        'table_number' => $table_number,
        'notes' => $notes,
        'discount' => $input['discount'] ?? 0
    ]);
    
    $stmt = $conn->prepare("INSERT INTO held_orders (order_number, customer_id, customer_phone, subtotal, discount, discount_amount, total_amount, order_data, created_by, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'held')");
    $stmt->bind_param("sisdddsss", $order_number, $customer_id, $customer_phone, $subtotal, $discount, $discount_amount, $total_amount, $order_data_with_details, $created_by);
    
    if ($stmt->execute()) {
        $held_order_id = $conn->insert_id;
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Order held successfully',
            'order_number' => $order_number,
            'order_id' => $held_order_id,
            'total_amount' => $total_amount
        ]);
    } else {
        throw new Exception('Failed to save held order: ' . $stmt->error);
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false, 
        'message' => 'Error saving held order: ' . $e->getMessage()
    ]);
}

$conn->close();
?>