<?php
/**
 * Kitchen -> Purchase Manager requisition API
 * Creates purchase requisitions directly from kitchen low-stock checks.
 */

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

if (!isset($_SESSION['kitchen_staff_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Kitchen session required']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Only POST allowed']);
    exit;
}

function hasColumn($conn, $table, $column) {
    $table = $conn->real_escape_string($table);
    $column = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
    return $res && $res->num_rows > 0;
}

function firstActivePurchaseManagerId($conn) {
    $res = $conn->query("SELECT id FROM purchase_managers WHERE status = 'active' ORDER BY id ASC LIMIT 1");
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        return (int)$row['id'];
    }
    return 0;
}

$input = json_decode(file_get_contents('php://input'), true);
$ingredient_id = isset($input['ingredient_id']) && $input['ingredient_id'] !== '' ? (int)$input['ingredient_id'] : null;
$item_description = trim((string)($input['item_description'] ?? ''));
$unit = trim((string)($input['unit'] ?? ''));
$quantity = isset($input['quantity']) ? (float)$input['quantity'] : 0;
$priority = (string)($input['priority'] ?? 'high');
$needed_by_date = trim((string)($input['needed_by_date'] ?? ''));
$notes = trim((string)($input['notes'] ?? ''));

if ($ingredient_id && ($item_description === '' || $unit === '')) {
    $stmt = $conn->prepare("SELECT name, unit FROM ingredients WHERE id = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param('i', $ingredient_id);
        $stmt->execute();
        $ing = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($ing) {
            if ($item_description === '') $item_description = $ing['name'];
            if ($unit === '') $unit = $ing['unit'];
        }
    }
}

if ($item_description === '' || $unit === '' || $quantity <= 0) {
    echo json_encode(['success' => false, 'message' => 'Item, quantity and unit are required']);
    exit;
}

if (!in_array($priority, ['low', 'medium', 'high', 'urgent'], true)) {
    $priority = 'high';
}

$pm_id = firstActivePurchaseManagerId($conn);
if ($pm_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'No active purchase manager found']);
    exit;
}

$hasIngredientId = hasColumn($conn, 'purchase_requisitions', 'ingredient_id');
$hasPriority = hasColumn($conn, 'purchase_requisitions', 'priority');
$hasRequestedByRole = hasColumn($conn, 'purchase_requisitions', 'requested_by_role');
$hasRequestedByName = hasColumn($conn, 'purchase_requisitions', 'requested_by_name');
$hasNeededByDate = hasColumn($conn, 'purchase_requisitions', 'needed_by_date');
$hasNotes = hasColumn($conn, 'purchase_requisitions', 'notes');
$hasOrderedStatus = $hasPriority; // new enum includes ordered

$statuses = $hasOrderedStatus ? "'pending','approved','ordered'" : "'pending','approved'";

if ($hasIngredientId && $ingredient_id) {
    $checkSql = "SELECT id FROM purchase_requisitions WHERE purchase_manager_id = ? AND ingredient_id = ? AND status IN ($statuses) LIMIT 1";
    $check = $conn->prepare($checkSql);
    $check->bind_param('ii', $pm_id, $ingredient_id);
} else {
    $checkSql = "SELECT id FROM purchase_requisitions WHERE purchase_manager_id = ? AND item_description = ? AND unit = ? AND status IN ($statuses) LIMIT 1";
    $check = $conn->prepare($checkSql);
    $check->bind_param('iss', $pm_id, $item_description, $unit);
}

if (!$check) {
    echo json_encode(['success' => false, 'message' => 'Failed to check duplicates: ' . $conn->error]);
    exit;
}

$check->execute();
$existing = $check->get_result()->fetch_assoc();
$check->close();

if ($existing) {
    echo json_encode([
        'success' => true,
        'message' => 'An open requisition already exists for this ingredient/item',
        'requisition_id' => (int)$existing['id'],
        'duplicate' => true
    ]);
    exit;
}

$kitchenName = (string)($_SESSION['kitchen_staff_name'] ?? 'Kitchen Staff');
$neededBy = $needed_by_date !== '' ? $needed_by_date : null;

if ($hasPriority && $hasRequestedByRole && $hasRequestedByName && $hasNeededByDate) {
    $sql = "
        INSERT INTO purchase_requisitions (
            purchase_manager_id, ingredient_id, item_description, quantity, unit,
            priority, requested_by_role, requested_by_name, needed_by_date, status, notes, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, 'kitchen', ?, ?, 'pending', ?, NOW())
    ";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Insert prepare failed: ' . $conn->error]);
        exit;
    }

    $ingredientBind = $hasIngredientId ? $ingredient_id : null;
    $notesBind = $hasNotes ? $notes : '';
    $stmt->bind_param('iisdsssss', $pm_id, $ingredientBind, $item_description, $quantity, $unit, $priority, $kitchenName, $neededBy, $notesBind);
} else {
    $sql = "
        INSERT INTO purchase_requisitions (
            purchase_manager_id, item_description, quantity, unit, status, notes, created_at
        ) VALUES (?, ?, ?, ?, 'pending', ?, NOW())
    ";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Insert prepare failed: ' . $conn->error]);
        exit;
    }
    $legacyNotes = $notes !== '' ? $notes : ('Requested by kitchen: ' . $kitchenName);
    $stmt->bind_param('isdss', $pm_id, $item_description, $quantity, $unit, $legacyNotes);
}

if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Failed to create requisition: ' . $stmt->error]);
    $stmt->close();
    exit;
}

$newId = (int)$conn->insert_id;
$stmt->close();

echo json_encode([
    'success' => true,
    'message' => 'Kitchen requisition sent to Purchase Manager',
    'requisition_id' => $newId,
    'duplicate' => false
]);
