<?php
header('Content-Type: application/json');
require 'db_connect.php';

$data = json_decode(file_get_contents("php://input"));
$action = $data->action ?? '';
$uid = $conn->real_escape_string($data->user_id ?? '');

if ($action === 'save') {
    $client = $conn->real_escape_string($data->client);
    $product = $conn->real_escape_string($data->product);
    $date = $conn->real_escape_string($data->date); // El input type="date" ya envía YYYY-MM-DD
    $price = (float)$data->price;
    $phone = $conn->real_escape_string($data->phone);
    $status = $conn->real_escape_string($data->status ?? 'todo');

    $sql = "INSERT INTO orders (user_id, client_name, product, delivery_date, price, phone, status) 
            VALUES ('$uid', '$client', '$product', '$date', $price, '$phone', '$status')";
    echo json_encode(["success" => $conn->query($sql)]);
}
// ... resto de acciones list, move, delete se mantienen igual ...
if ($action === 'list') {
    $res = $conn->query("SELECT * FROM orders WHERE user_id = '$uid' ORDER BY delivery_date ASC");
    $orders = [];
    while($row = $res->fetch_assoc()) { $orders[] = $row; }
    echo json_encode($orders);
}
if ($action === 'move') {
    $oid = (int)$data->order_id;
    $newStatus = $conn->real_escape_string($data->status);
    $conn->query("UPDATE orders SET status = '$newStatus' WHERE id = $oid AND user_id = '$uid'");
    echo json_encode(["success" => true]);
}
if ($action === 'delete') {
    $oid = (int)$data->order_id;
    $conn->query("DELETE FROM orders WHERE id = $oid AND user_id = '$uid'");
    echo json_encode(["success" => true]);
}
$conn->close();
