<?php
// ============================================================
//  MediCore — Purchase Order Approval / Validation
//  File: includes/po_approval.php
//  Optional gate in front of the existing "save PO = instant
//  stock + ledger" flow. Off by default (Settings > Invoice tab);
//  when on, POs at/above a rupee threshold go to a Pending queue
//  instead of touching stock immediately.
// ============================================================

// ── Auto-migration: approval columns on purchases ───────────────
function ensure_po_approval_columns(): void {
    static $done = false;
    if ($done) return;
    $done = true;

    try {
        $hasCol = db_val(
            "SELECT COUNT(*) FROM information_schema.COLUMNS
              WHERE TABLE_SCHEMA = DATABASE()
                AND TABLE_NAME   = 'purchases'
                AND COLUMN_NAME  = 'approval_status'"
        );
        if (!$hasCol) {
            db_run("ALTER TABLE purchases
                ADD COLUMN approval_status ENUM('not_required','pending','approved','rejected')
                            DEFAULT 'not_required',
                ADD COLUMN submitted_by     INT UNSIGNED DEFAULT NULL,
                ADD COLUMN approved_by      INT UNSIGNED DEFAULT NULL,
                ADD COLUMN approved_at      DATETIME     DEFAULT NULL,
                ADD COLUMN rejection_reason VARCHAR(500) DEFAULT '',
                ADD COLUMN account          VARCHAR(50)  DEFAULT 'Cash'");
            db_run("ALTER TABLE purchases ADD INDEX idx_purchases_approval (approval_status)");
        }
    } catch (Throwable $e) {
        error_log('ensure_po_approval_columns failed: ' . $e->getMessage());
    }
}

// ── Settings readers ─────────────────────────────────────────────
function po_approval_enabled(): bool {
    $cfg = get_settings();
    return ($cfg['po_approval_enabled'] ?? '0') === '1';
}

function po_approval_threshold(): float {
    $cfg = get_settings();
    return (float) ($cfg['po_approval_threshold'] ?? 0);
}

// A purchase order needs to go through the approval queue when the
// workflow is switched on AND its total is at/above the threshold.
// Threshold of 0 (the default once enabled) means "everything".
function po_needs_approval(float $finalPrice): bool {
    if (!po_approval_enabled()) return false;
    return $finalPrice >= po_approval_threshold();
}

// ── Who can approve/reject ───────────────────────────────────────
function can_approve_po(): bool {
    return is_admin() || current_user_role() === 'manager';
}
