<?php
include("../config/config.php");

// Step 1: Get pending feedbacks where time expired
$sql = "
    SELECT f.feedback_id, f.department_id, f.current_level
    FROM feedbacks f
    WHERE f.responded = 0 
      AND f.next_escalation_time <= NOW()
";
$result = $con->query($sql);

while ($row = $result->fetch_assoc()) {
    $feedback_id = $row['feedback_id'];
    $department_id = $row['department_id'];
    $current_level = $row['current_level'];

    // Step 2: Find next level user
    $next_query = $con->prepare("
        SELECT user_id, escalation_level
        FROM escalation_mapping 
        WHERE department_id=? AND escalation_level=? 
        LIMIT 1
    ");
    $next_level = $current_level + 1;
    $next_query->bind_param("ii", $department_id, $next_level);
    $next_query->execute();
    $next_query->bind_result($next_user_id, $escalation_level);
    $next_query->fetch();
    $next_query->close();

    // Step 3: If next level exists → escalate
    if (!empty($next_user_id)) {
        $update = $con->prepare("
            UPDATE feedbacks 
            SET admin_id=?, current_level=?, next_escalation_time=DATE_ADD(NOW(), INTERVAL 24 HOUR)
            WHERE feedback_id=?
        ");
        $update->bind_param("iii", $next_user_id, $escalation_level, $feedback_id);
        $update->execute();
        $update->close();
        echo "Feedback ID $feedback_id escalated to level $escalation_level (User ID: $next_user_id)<br>";
    } else {
        // Step 4: No next level — stop escalation
        $update = $con->prepare("
            UPDATE feedbacks 
            SET next_escalation_time=NULL 
            WHERE feedback_id=?
        ");
        $update->bind_param("i", $feedback_id);
        $update->execute();
        $update->close();
        echo "Feedback ID $feedback_id reached final escalation level. Stopped.<br>";
    }
}
?>
