<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? '';

switch ($action) {
    case 'save':
        $order = $data['order'];
        $id = $order['id'] ?? '';
        $lineId = !empty($order['production_line_id']) ? $order['production_line_id'] : null;
        
        if ($id) {
            $sql = "UPDATE orders SET order_no=?, product_name=?, buyer_id=?, qty=?, current_stage=?, progress=?, deadline=?, production_line_id=? WHERE id=?";
            query($sql, [$order['order_no'], $order['product_name'], $order['buyer_id'], $order['qty'], $order['current_stage'], $order['progress'], $order['deadline'], $lineId, $id]);
            echo json_encode(['success' => true, 'message' => 'Order updated successfully']);
        } else {
            $sql = "INSERT INTO orders (order_no, product_name, buyer_id, qty, current_stage, progress, deadline, production_line_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            query($sql, [$order['order_no'], $order['product_name'], $order['buyer_id'], $order['qty'], $order['current_stage'], $order['progress'], $order['deadline'], $lineId]);
            echo json_encode(['success' => true, 'message' => 'New order created successfully']);
        }
        break;

    case 'delete':
        $id = $data['id'];
        query("DELETE FROM orders WHERE id = ?", [$id]);
        echo json_encode(['success' => true, 'message' => 'Order deleted successfully']);
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
