<?php
namespace App\Copilot\Tools;

use App\Copilot\CopilotTool;
use App\Core\Database;
use App\Core\Tenant;

class ProposePurchaseOrder implements CopilotTool
{
    public function name(): string { return 'propose_purchase_order'; }

    public function description(): string
    {
        return 'Proposes a purchase order to a supplier. Returns a proposal that must be approved by a human unless policy allows auto-execution.';
    }

    public function parameters(): array
    {
        return [
            'type' => 'object',
            'properties' => [
                'supplier_id' => ['type' => 'integer', 'description' => 'Supplier ID'],
                'lines'       => [
                    'type' => 'array',
                    'items' => [
                        'type' => 'object',
                        'properties' => [
                            'product_id' => ['type' => 'integer'],
                            'qty'        => ['type' => 'number'],
                            'unit_cost'  => ['type' => 'number'],
                        ],
                        'required' => ['product_id', 'qty'],
                    ],
                ],
                'note' => ['type' => 'string'],
            ],
            'required' => ['supplier_id', 'lines'],
        ];
    }

    public function execute(array $args): array
    {
        $supplier = Database::fetch("SELECT id, name FROM suppliers WHERE id = ? AND tenant_id = ?",
            [(int)$args['supplier_id'], Tenant::id()]);
        if (!$supplier) return ['error' => 'Supplier not found'];

        $lines = $args['lines'] ?? [];
        if (!$lines) return ['error' => 'No lines provided'];

        $total = 0;
        $enriched = [];
        foreach ($lines as $l) {
            $product = Database::fetch("SELECT id, name, sku, cost_price FROM products WHERE id = ? AND tenant_id = ?",
                [(int)$l['product_id'], Tenant::id()]);
            if (!$product) return ['error' => "Product {$l['product_id']} not found"];
            $cost = (float)($l['unit_cost'] ?? $product['cost_price']);
            $lineTotal = $cost * (float)$l['qty'];
            $total += $lineTotal;
            $enriched[] = [
                'product_id' => (int)$product['id'],
                'name'       => $product['name'],
                'sku'        => $product['sku'],
                'qty'        => (float)$l['qty'],
                'unit_cost'  => $cost,
                'line_total' => $lineTotal,
            ];
        }

        $policy = PolicyEngine::policy(Tenant::id());
        $maxValue = (float)($policy['max_po_value'] ?? 5000);

        return [
            'summary' => "PO to {$supplier['name']} — " . count($enriched) . " lines, total " . number_format($total, 2),
            'within_policy' => $total <= $maxValue,
            'action' => [
                'type' => 'purchase_order',
                'payload' => [
                    'supplier_id' => (int)$supplier['id'],
                    'supplier_name' => $supplier['name'],
                    'lines' => $enriched,
                    'total' => $total,
                    'note' => $args['note'] ?? null,
                ],
            ],
        ];
    }

    public function apply(array $payload): void
    {
        Database::transaction(function ($pdo) use ($payload) {
            $reference = 'PO-' . date('Ymd-His') . '-AI';
            $pdo->prepare(
                "INSERT INTO purchases (tenant_id, reference_no, supplier_id, user_id, subtotal, total, status)
                 VALUES (?, ?, ?, 0, ?, ?, 'pending')"
            )->execute([Tenant::id(), $reference, (int)$payload['supplier_id'], (float)$payload['total'], (float)$payload['total']]);
            $purchaseId = (int)$pdo->lastInsertId();

            $stmt = $pdo->prepare(
                "INSERT INTO purchase_items (purchase_id, product_id, qty, unit_cost, line_total) VALUES (?, ?, ?, ?, ?)"
            );
            foreach ($payload['lines'] as $l) {
                $stmt->execute([$purchaseId, (int)$l['product_id'], (float)$l['qty'], (float)$l['unit_cost'], (float)$l['line_total']]);
            }
        });
    }
}