<?php
/**
 * Purchase Orders 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
            po.id,
            po.po_number,
            po.requisition_id,
            po.supplier_id,
            po.ingredient_id,
            po.item_name,
            po.quantity,
            po.unit,
            po.unit_price,
            po.total_cost,
            po.received_quantity,
            po.status,
            po.created_at,
            po.expected_delivery_date,
            po.delivery_date,
            po.invoice_number,
            po.notes,
            s.name AS supplier_name,
            i.current_stock,
            i.minimum_stock,
            pr.priority AS requisition_priority
        FROM purchase_orders po
        LEFT JOIN suppliers s ON po.supplier_id = s.id
        LEFT JOIN ingredients i ON po.ingredient_id = i.id
        LEFT JOIN purchase_requisitions pr ON po.requisition_id = pr.id
        WHERE po.purchase_manager_id = ?
        ORDER BY po.created_at DESC
    ");
    $stmt->bind_param('i', $pm_id);
    $stmt->execute();
    $result = $stmt->get_result();

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

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

if ($action === 'get_suppliers') {
    $stmt = $conn->prepare("
        SELECT id, name, rating, lead_time_days, payment_terms
        FROM suppliers
        WHERE purchase_manager_id = ? AND status = 'active'
        ORDER BY name ASC
    ");
    $stmt->bind_param('i', $pm_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $suppliers = [];
    while ($row = $result->fetch_assoc()) {
        $suppliers[] = $row;
    }
    echo json_encode(['success' => true, 'suppliers' => $suppliers]);
    exit;
}

if ($action === 'get_approved_requisitions') {
    $stmt = $conn->prepare("
        SELECT
            pr.id,
            pr.ingredient_id,
            pr.item_description,
            pr.quantity,
            pr.unit,
            pr.priority,
            pr.needed_by_date
        FROM purchase_requisitions pr
        LEFT JOIN purchase_orders po ON po.requisition_id = pr.id
        WHERE pr.purchase_manager_id = ?
          AND pr.status = 'approved'
          AND po.id IS NULL
        ORDER BY pr.created_at ASC
    ");
    $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 === 'create') {
    $data = is_array($payload) ? $payload : [];

    $supplier_id = isset($data['supplier_id']) ? (int)$data['supplier_id'] : 0;
    $requisition_id = isset($data['requisition_id']) && $data['requisition_id'] !== '' ? (int)$data['requisition_id'] : null;
    $ingredient_id = isset($data['ingredient_id']) && $data['ingredient_id'] !== '' ? (int)$data['ingredient_id'] : null;
    $item_name = trim($data['item_name'] ?? '');
    $quantity = isset($data['quantity']) ? (float)$data['quantity'] : 0;
    $unit = trim($data['unit'] ?? '');
    $unit_price = isset($data['unit_price']) ? (float)$data['unit_price'] : 0;
    $expected_delivery_date = trim($data['expected_delivery_date'] ?? '');
    $notes = trim($data['notes'] ?? '');

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

    if ($requisition_id) {
        $reqStmt = $conn->prepare("
            SELECT ingredient_id, item_description, quantity, unit
            FROM purchase_requisitions
            WHERE id = ? AND purchase_manager_id = ? AND status IN ('approved', 'ordered')
        ");
        $reqStmt->bind_param('ii', $requisition_id, $pm_id);
        $reqStmt->execute();
        $req = $reqStmt->get_result()->fetch_assoc();
        if (!$req) {
            echo json_encode(['success' => false, 'message' => 'Approved requisition not found']);
            exit;
        }
        if ($item_name === '') {
            $item_name = $req['item_description'];
        }
        if (!$ingredient_id && !empty($req['ingredient_id'])) {
            $ingredient_id = (int)$req['ingredient_id'];
        }
    }

    if ($item_name === '') {
        echo json_encode(['success' => false, 'message' => 'Item name is required']);
        exit;
    }

    $total_cost = $quantity * $unit_price;
    $po_number = 'PO-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid((string)$pm_id, true)), 0, 6));
    $eta = $expected_delivery_date !== '' ? $expected_delivery_date : null;

    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare("
            INSERT INTO purchase_orders (
                purchase_manager_id, requisition_id, supplier_id, ingredient_id, po_number, item_name,
                quantity, unit, unit_price, total_cost, status, created_at, expected_delivery_date, notes
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'confirmed', NOW(), ?, ?)
        ");
        $stmt->bind_param(
            'iiiissdsddss',
            $pm_id,
            $requisition_id,
            $supplier_id,
            $ingredient_id,
            $po_number,
            $item_name,
            $quantity,
            $unit,
            $unit_price,
            $total_cost,
            $eta,
            $notes
        );

        if (!$stmt->execute()) {
            throw new Exception('Failed to create purchase order');
        }

        if ($requisition_id) {
            $reqUpdate = $conn->prepare("
                UPDATE purchase_requisitions
                SET status = 'ordered'
                WHERE id = ? AND purchase_manager_id = ?
            ");
            $reqUpdate->bind_param('ii', $requisition_id, $pm_id);
            if (!$reqUpdate->execute()) {
                throw new Exception('Failed to update requisition status');
            }
        }

        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Purchase order created', 'po_number' => $po_number]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'create_batch_document') {
    $data = is_array($payload) ? $payload : [];
    $items = isset($data['items']) && is_array($data['items']) ? $data['items'] : [];
    $expected_delivery_date = trim($data['expected_delivery_date'] ?? '');
    $notes = trim($data['notes'] ?? '');

    if (count($items) === 0) {
        echo json_encode(['success' => false, 'message' => 'At least one item is required']);
        exit;
    }

    $po_number = 'PO-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid((string)$pm_id, true)), 0, 6));
    $eta = $expected_delivery_date !== '' ? $expected_delivery_date : null;

    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare("
            INSERT INTO purchase_orders (
                purchase_manager_id, requisition_id, supplier_id, ingredient_id, po_number, item_name,
                quantity, unit, unit_price, total_cost, status, created_at, expected_delivery_date, notes
            ) VALUES (?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, 'confirmed', NOW(), ?, ?)
        ");
        if (!$stmt) {
            throw new Exception('Failed to prepare batch insert');
        }

        $created_count = 0;
        foreach ($items as $idx => $item) {
            $supplier_id = isset($item['supplier_id']) ? (int)$item['supplier_id'] : 0;
            $ingredient_id = isset($item['ingredient_id']) && $item['ingredient_id'] !== '' ? (int)$item['ingredient_id'] : null;
            $item_name = trim($item['item_name'] ?? '');
            $quantity = isset($item['quantity']) ? (float)$item['quantity'] : 0;
            $unit = trim($item['unit'] ?? '');
            $unit_price = isset($item['unit_price']) ? (float)$item['unit_price'] : 0;
            $line_eta = trim($item['expected_delivery_date'] ?? '');
            $line_notes = trim($item['notes'] ?? '');

            if ($supplier_id <= 0 || $item_name === '' || $quantity <= 0 || $unit === '') {
                throw new Exception('Invalid item at line ' . ($idx + 1) . ': supplier, item name, quantity and unit are required');
            }

            $total_cost = $quantity * $unit_price;
            $resolved_eta = $line_eta !== '' ? $line_eta : $eta;
            $resolved_notes = $line_notes !== '' ? $line_notes : $notes;

            $stmt->bind_param(
                'iiissdsddss',
                $pm_id,
                $supplier_id,
                $ingredient_id,
                $po_number,
                $item_name,
                $quantity,
                $unit,
                $unit_price,
                $total_cost,
                $resolved_eta,
                $resolved_notes
            );

            if (!$stmt->execute()) {
                throw new Exception('Failed to create line ' . ($idx + 1));
            }
            $created_count++;
        }

        $conn->commit();
        echo json_encode([
            'success' => true,
            'message' => 'Combined purchase order created',
            'po_number' => $po_number,
            'line_count' => $created_count
        ]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

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

    if (!in_array($status, ['draft', 'confirmed', 'shipped', 'partially_received', 'delivered', 'cancelled'], true)) {
        echo json_encode(['success' => false, 'message' => 'Invalid status']);
        exit;
    }

    $stmt = $conn->prepare("
        UPDATE purchase_orders
        SET status = ?
        WHERE id = ? AND purchase_manager_id = ?
    ");
    $stmt->bind_param('sii', $status, $id, $pm_id);
    $ok = $stmt->execute();
    echo json_encode(['success' => $ok, 'message' => $ok ? 'Order status updated' : 'Failed to update status']);
    exit;
}

if ($action === 'receive_stock') {
    $data = is_array($payload) ? $payload : [];
    $id = isset($data['id']) ? (int)$data['id'] : 0;
    $received_qty = isset($data['received_quantity']) ? (float)$data['received_quantity'] : 0;
    $invoice_number = trim($data['invoice_number'] ?? '');
    $notes = trim($data['notes'] ?? '');

    if ($id <= 0 || $received_qty <= 0) {
        echo json_encode(['success' => false, 'message' => 'Order and received quantity are required']);
        exit;
    }

    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare("
            SELECT id, ingredient_id, quantity, received_quantity, status
            FROM purchase_orders
            WHERE id = ? AND purchase_manager_id = ?
            FOR UPDATE
        ");
        $stmt->bind_param('ii', $id, $pm_id);
        $stmt->execute();
        $order = $stmt->get_result()->fetch_assoc();

        if (!$order) {
            throw new Exception('Purchase order not found');
        }

        $new_received = (float)$order['received_quantity'] + $received_qty;
        if ($new_received > (float)$order['quantity']) {
            throw new Exception('Received quantity exceeds ordered quantity');
        }

        $new_status = $new_received >= (float)$order['quantity'] ? 'delivered' : 'partially_received';
        $delivery_date = $new_status === 'delivered' ? date('Y-m-d H:i:s') : null;

        $update = $conn->prepare("
            UPDATE purchase_orders
            SET received_quantity = ?, status = ?, delivery_date = COALESCE(?, delivery_date),
                invoice_number = COALESCE(NULLIF(?, ''), invoice_number),
                notes = CASE WHEN ? = '' THEN notes ELSE CONCAT(COALESCE(notes, ''), '\n', ?) END
            WHERE id = ? AND purchase_manager_id = ?
        ");
        $update->bind_param('dsssssii', $new_received, $new_status, $delivery_date, $invoice_number, $notes, $notes, $id, $pm_id);
        if (!$update->execute()) {
            throw new Exception('Failed to update purchase order receive status');
        }

        if (!empty($order['ingredient_id'])) {
            $stock = $conn->prepare("
                UPDATE ingredients
                SET current_stock = current_stock + ?
                WHERE id = ?
            ");
            $stock->bind_param('di', $received_qty, $order['ingredient_id']);
            if (!$stock->execute()) {
                throw new Exception('Failed to update ingredient stock');
            }
        }

        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Stock received and inventory updated']);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'delete') {
    $data = is_array($payload) ? $payload : [];
    $id = isset($data['id']) ? (int)$data['id'] : 0;
    $stmt = $conn->prepare("
        DELETE FROM purchase_orders
        WHERE id = ? AND purchase_manager_id = ? AND status IN ('draft', 'cancelled')
    ");
    $stmt->bind_param('ii', $id, $pm_id);
    $ok = $stmt->execute();
    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Order deleted' : 'Only draft/cancelled orders can be deleted'
    ]);
    exit;
}

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