<?php
/**
 * Server Order Ready Notification API
 * Called by kitchen when order is ready for pickup
 * Stores notification flag so server dashboard can display it
 */

session_start();
header('Content-Type: application/json');
require_once 'config.php';

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

if (!$input || !isset($input['order_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request. Missing order_id.'
    ]);
    exit;
}

$order_id = (int)$input['order_id'];

try {
    // Verify order exists and get server info
    $stmt = $conn->prepare("
        SELECT id, server_id, status FROM dine_in_orders WHERE id = ?
    ");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Order not found'
        ]);
        $stmt->close();
        exit;
    }
    
    $order = $result->fetch_assoc();
    $stmt->close();
    
    // Create notification table if it doesn't exist
    $create_table_sql = "CREATE TABLE IF NOT EXISTS order_notifications (
        id INT PRIMARY KEY AUTO_INCREMENT,
        order_id INT NOT NULL,
        server_id INT NOT NULL,
        notification_type VARCHAR(50) DEFAULT 'ready',
        message TEXT,
        is_read INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (order_id) REFERENCES dine_in_orders(id) ON DELETE CASCADE,
        FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE
    )";
    $conn->query($create_table_sql);
    
    // Create notification record
    $message = "Your order is ready for pickup!";
    $stmt = $conn->prepare("
        INSERT INTO order_notifications (order_id, server_id, notification_type, message, is_read)
        VALUES (?, ?, 'ready', ?, 0)
    ");
    $stmt->bind_param("iss", $order_id, $order['server_id'], $message);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create notification: ' . $stmt->error);
    }
    
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'message' => 'Server notified successfully',
        'order_id' => $order_id,
        'notification_type' => 'ready'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
