<?php
/**
 * Purchase Requisitions API
 */

session_start();
include 'config.php';

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

$pm_id = (int)$_SESSION['purchase_manager_id'];
$action = isset($_GET['action']) ? $_GET['action'] : '';
$rawInput = file_get_contents('php://input');
$payload = json_decode($rawInput, true);
if (!$action && is_array($payload)) {
    $action = $payload['action'] ?? '';
}

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

if ($action === 'get_all') {
    $stmt = $conn->prepare("
        SELECT
            pr.id,
            pr.ingredient_id,
            pr.item_description,
            pr.quantity,
            pr.unit,
            pr.priority,
            pr.requested_by_role,
            pr.requested_by_name,
            pr.needed_by_date,
            pr.status,
            pr.created_at,
            pr.approval_date,
            pr.rejection_reason,
            pr.notes,
            i.name AS ingredient_name,
            i.current_stock,
            i.minimum_stock,
            po.id AS purchase_order_id
        FROM purchase_requisitions pr
        LEFT JOIN ingredients i ON pr.ingredient_id = i.id
        LEFT JOIN purchase_orders po ON po.requisition_id = pr.id
        WHERE pr.purchase_manager_id = ?
          AND pr.status IN ('pending', 'approved')
          AND po.id IS NULL
        ORDER BY pr.created_at DESC
    ");
    $stmt->bind_param('i', $pm_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $requisitions = [];
    while ($row = $result->fetch_assoc()) {
        $requisitions[] = $row;
    }

    echo json_encode(['success' => true, 'requisitions' => $requisitions]);
    exit;
}

if ($action === 'get_ingredients') {
    $result = $conn->query("
        SELECT id, name, unit, current_stock, minimum_stock, status
        FROM ingredients
        WHERE status = 'active'
        ORDER BY name ASC
    ");
    $ingredients = [];
    while ($row = $result->fetch_assoc()) {
        $ingredients[] = $row;
    }
    echo json_encode(['success' => true, 'ingredients' => $ingredients]);
    exit;
}

if ($action === 'create') {
    $data = is_array($payload) ? $payload : [];

    $ingredient_id = isset($data['ingredient_id']) && $data['ingredient_id'] !== '' ? (int)$data['ingredient_id'] : null;
    $item_description = trim($data['item_description'] ?? '');
    $quantity = isset($data['quantity']) ? (float)$data['quantity'] : 0;
    $unit = trim($data['unit'] ?? '');
    $priority = in_array(($data['priority'] ?? 'medium'), ['low', 'medium', 'high', 'urgent'], true) ? $data['priority'] : 'medium';
    $requested_by_name = trim($data['requested_by_name'] ?? 'Kitchen');
    $needed_by_date = trim($data['needed_by_date'] ?? '');
    $notes = trim($data['notes'] ?? '');

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

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

    $neededBy = $needed_by_date !== '' ? $needed_by_date : null;

    $stmt = $conn->prepare("
        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->bind_param('iisdsssss', $pm_id, $ingredient_id, $item_description, $quantity, $unit, $priority, $requested_by_name, $neededBy, $notes);
    $ok = $stmt->execute();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Requisition created' : 'Failed to create requisition',
        'id' => $ok ? $conn->insert_id : null
    ]);
    exit;
}

if ($action === 'update_status') {
    $data = is_array($payload) ? $payload : [];
    $id = isset($data['id']) ? (int)$data['id'] : 0;
    $status = $data['status'] ?? '';
    $notes = trim($data['notes'] ?? '');
    $rejection_reason = trim($data['rejection_reason'] ?? '');

    if (!in_array($status, ['approved', 'rejected', 'ordered', 'closed'], true)) {
        echo json_encode(['success' => false, 'message' => 'Invalid status transition']);
        exit;
    }

    if ($status === 'rejected' && $rejection_reason === '') {
        echo json_encode(['success' => false, 'message' => 'Rejection reason is required']);
        exit;
    }

    $approvalDate = $status === 'approved' ? date('Y-m-d H:i:s') : null;

    $stmt = $conn->prepare("
        UPDATE purchase_requisitions
        SET status = ?, approval_date = ?, approved_by_manager_id = ?, rejection_reason = ?, notes = COALESCE(NULLIF(?, ''), notes)
        WHERE id = ? AND purchase_manager_id = ?
    ");
    $stmt->bind_param('ssissii', $status, $approvalDate, $pm_id, $rejection_reason, $notes, $id, $pm_id);
    $ok = $stmt->execute();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Requisition updated' : 'Failed to update requisition'
    ]);
    exit;
}

if ($action === 'delete') {
    $data = is_array($payload) ? $payload : [];
    $id = isset($data['id']) ? (int)$data['id'] : 0;

    $stmt = $conn->prepare("
        DELETE FROM purchase_requisitions
        WHERE id = ? AND purchase_manager_id = ? AND status = 'pending'
    ");
    $stmt->bind_param('ii', $id, $pm_id);
    $ok = $stmt->execute();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Requisition deleted' : 'Only pending requisitions can be deleted'
    ]);
    exit;
}

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