<?php
require('include/functions.php');

// 1. Get current Flows
$row = sb_db_get("SELECT value FROM sb_settings WHERE name = 'open-ai-flows'");
if (!$row) {
    die("Error: 'open-ai-flows' setting not found in DB.\n");
}

$flows_json = $row['value'];
$flows = json_decode($flows_json, true);

if (!$flows) {
    die("Error: Failed to decode JSON.\n");
}

echo "Found " . count($flows) . " flows.\n";

$target_flow_name = 'usmle_copy';
$found = false;
$new_triggers = [
    'الاسئله الشائعه',
    'الاسئلة الشائعه',
    'الأسئله الشائعه',
    'أسعار الكورسات',
    'اسعار الكورسات'
];

foreach ($flows as &$flow) {
    if ($flow['name'] == $target_flow_name) {
        $found = true;
        echo "Found flow: $target_flow_name\n";
        
        // Locate Triggers container (Step 0)
        if (isset($flow['steps'][0][0][0]['message'])) {
            $current_triggers = $flow['steps'][0][0][0]['message'];
            echo "Current triggers count: " . count($current_triggers) . "\n";
            
            // Extract existing strings to check duplicates
            $existing_strings = [];
            foreach ($current_triggers as $t) {
                if (isset($t['message'])) {
                    $existing_strings[] = trim($t['message']);
                }
            }
            
            // Add new triggers
            $added_count = 0;
            foreach ($new_triggers as $nt) {
                if (!in_array($nt, $existing_strings)) {
                    $flow['steps'][0][0][0]['message'][] = ['message' => $nt];
                    echo "Adding trigger: [$nt]\n";
                    $added_count++;
                } else {
                    echo "Trigger exists: [$nt]\n";
                }
            }
            
            if ($added_count > 0) {
                echo "Added $added_count new triggers.\n";
            } else {
                echo "No new triggers added (all exist).\n";
            }
        } else {
            // Initialize if missing
             if (isset($flow['steps'][0][0][0])) {
                 echo "Step 0 found but 'message' key missing. Initializing...\n";
                 $flow['steps'][0][0][0]['message'] = [];
                 foreach ($new_triggers as $nt) {
                    $flow['steps'][0][0][0]['message'][] = ['message' => $nt];
                 }
             }
        }
        break; // Stop after finding target
    }
}

if ($found) {
    // 2. Save back to DB
    $new_json = json_encode($flows, JSON_UNESCAPED_UNICODE);
    $new_json_escaped = sb_db_escape($new_json);
    
    if (strlen($new_json) > 100) {
        sb_db_query("UPDATE sb_settings SET value = '$new_json_escaped' WHERE name = 'open-ai-flows'");
        echo "SUCCESS: Flows updated in DB.\n";
    } else {
        echo "Error: New JSON seems invalid/short.\n";
    }
} else {
    echo "Error: Flow '$target_flow_name' not found.\n";
}
?>
