<?php
/**
 * EDM CORE — Operations Library
 * Enterprise Escalation Engine (Clean Version)
 */

if (!function_exists('ops_escalate_if_overdue')) {

function ops_escalate_if_overdue(PDO $pdo, int $company_id): int
{
    $stmt = $pdo->prepare("
        SELECT id
        FROM operations_tickets
        WHERE company_id = ?
          AND due_at IS NOT NULL
          AND due_at < NOW()
          AND status NOT IN ('Resolved','Closed','Escalated')
        ORDER BY due_at ASC
        LIMIT 200
    ");

    $stmt->execute([$company_id]);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$tickets) {
        return 0;
    }

    $updated = 0;

    $logStmt = $pdo->prepare("
        INSERT INTO operations_ticket_events
        (ticket_id, event_type, message, created_by, created_at)
        VALUES (?, 'ESCALATED', 'SLA breached automatically by system', NULL, NOW())
    ");

    $updStmt = $pdo->prepare("
        UPDATE operations_tickets
        SET status = 'Escalated',
            priority = CASE
                WHEN priority IN ('Low','Medium') THEN 'High'
                ELSE priority
            END
        WHERE company_id = ?
          AND id = ?
          AND status <> 'Escalated'
    ");

    foreach ($tickets as $t) {

        try {
            $pdo->beginTransaction();

            $updStmt->execute([$company_id, (int)$t['id']]);

            if ($updStmt->rowCount() > 0) {
                $logStmt->execute([(int)$t['id']]);
                $updated++;
            }

            $pdo->commit();

        } catch (Throwable $e) {

            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            // Optional: log error if you later implement error logging
        }
    }

    return $updated;
}

}

function pip_move_to_review($pdo, $company_id)
{
    $stmt = $pdo->prepare("
        UPDATE operations_tickets
        SET pip_stage = 'Review'
        WHERE company_id = ?
        AND category = 'Performance / PIP'
        AND pip_stage = 'Active'
        AND pip_review_date <= NOW()
        AND status NOT IN ('Resolved','Closed')
    ");

    $stmt->execute([$company_id]);
}