<?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';

function hasUnreadReadyNotification($conn, $order_id, $server_id) {
    $stmt = $conn->prepare("
        SELECT id
        FROM order_notifications
        WHERE order_id = ?
          AND server_id = ?
          AND notification_type = 'ready'
          AND is_read = 0
        LIMIT 1
    ");
    if (!$stmt) {
        throw new Exception('Failed to prepare notification lookup: ' . $conn->error);
    }

    $stmt->bind_param("ii", $order_id, $server_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $exists = $result && $result->num_rows > 0;
    $stmt->close();

    return $exists;
}

$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,
        item_id INT 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);

    $item_id_col = $conn->query("SHOW COLUMNS FROM order_notifications LIKE 'item_id'");
    if (!$item_id_col || $item_id_col->num_rows === 0) {
        if (!$conn->query("ALTER TABLE order_notifications ADD COLUMN item_id INT NULL AFTER server_id")) {
            throw new Exception('Failed to add item_id to order_notifications: ' . $conn->error);
        }
    }
    
    $server_id = (int)$order['server_id'];

    if (hasUnreadReadyNotification($conn, $order_id, $server_id)) {
        echo json_encode([
            'success' => true,
            'message' => 'Server already has an unread ready notification for this order',
            'order_id' => $order_id,
            'notification_type' => 'ready',
            'duplicate' => true
        ]);
        exit;
    }

    // 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("iis", $order_id, $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()
    ]);
}
?>
