<?php
/**
 * Sudanna v23.2 — Deploy Script
 * Run ONCE then DELETE immediately
 * Access: /deploy.php?token=sudanna_deploy_2026
 */
// Security: token from env + optional IP whitelist
$expectedToken = $_ENV['DEPLOY_TOKEN'] ?? '';
if (empty($expectedToken)) {
    http_response_code(403);
    die(json_encode(['error'=>'deploy_disabled','message'=>'Set DEPLOY_TOKEN in .env to enable']));
}
if (!hash_equals($expectedToken, (string)($_GET['token'] ?? ''))) {
    http_response_code(403);
    die(json_encode(['error'=>'forbidden']));
}
// Optional IP whitelist
$allowedIps = array_filter(explode(',', $_ENV['DEPLOY_ALLOWED_IPS'] ?? ''));
if ($allowedIps && !in_array($_SERVER['REMOTE_ADDR'] ?? '', $allowedIps, true)) {
    http_response_code(403);
    die(json_encode(['error'=>'ip_not_allowed']));
}
echo "<pre style='font-family:monospace;padding:20px;background:#000;color:#0f0;font-size:13px'>\n";
echo "=== Sudanna v23.2 Deploy Script ===\n\n";

// 1. Extract ZIP if needed
$zip_file = __DIR__.'/sudanna_v23.2_RELEASE.zip';
if(file_exists($zip_file)){
    echo "📦 Extracting ZIP...\n";
    $zip = new ZipArchive();
    if($zip->open($zip_file) === true){
        $zip->extractTo(__DIR__);
        $zip->close();
        echo "✅ ZIP extracted successfully\n";
        unlink($zip_file);
        echo "✅ ZIP deleted\n";
    } else {
        echo "❌ Failed to open ZIP\n";
    }
} else {
    echo "ℹ️ No ZIP found — files already extracted\n";
}

// 2. Check .env
echo "\n📋 Checking .env...\n";
if(file_exists(__DIR__.'/.env')){
    $env = file_get_contents(__DIR__.'/.env');
    $keys = ['DB_HOST','DB_NAME','DB_USER','DB_PASS','GEMINI_API_KEY','JWT_SECRET'];
    foreach($keys as $k){
        $has = strpos($env,$k.'=')!==false;
        echo ($has?"✅":"❌")." $k\n";
    }
} else {
    echo "❌ .env file missing! Create it from .env.example\n";
}

// 3. Test DB connection
echo "\n🗄️ Testing database...\n";
require_once __DIR__.'/env_loader.php';
require_once __DIR__.'/config.php';
try{
    $db = db();
    $tables = $db->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    echo "✅ DB connected | Tables found: ".count($tables)."\n";
    if(count($tables) < 50){
        echo "⚠️ Only ".count($tables)." tables — need to import sudanna_v22_schema_complete.sql!\n";
    } else {
        echo "✅ Schema looks complete (".count($tables)." tables)\n";
    }
    // Check users
    $users = (int)$db->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $providers = (int)$db->query("SELECT COUNT(*) FROM users WHERE provider_verified=1")->fetchColumn();
    echo "👥 Users: $users | Verified providers: $providers\n";
} catch(Exception $e){
    echo "❌ DB Error: ".$e->getMessage()."\n";
}

// 4. Check AI keys
echo "\n🤖 Checking AI keys...\n";
echo (strlen(GEMINI_API_KEY)>10?"✅":"❌")." GEMINI_API_KEY: ".(strlen(GEMINI_API_KEY)>10?substr(GEMINI_API_KEY,0,12)."...":"MISSING")."\n";
echo (strlen(CLAUDE_API_KEY)>10?"✅":"❌")." CLAUDE_API_KEY: ".(strlen(CLAUDE_API_KEY)>10?substr(CLAUDE_API_KEY,0,12)."...":"MISSING")."\n";
echo (strlen(OPENAI_API_KEY)>10?"✅":"❌")." OPENAI_API_KEY: ".(strlen(OPENAI_API_KEY)>10?substr(OPENAI_API_KEY,0,12)."...":"MISSING")."\n";

// 5. Check cron
echo "\n⏰ Worker cron check...\n";
if(function_exists('exec')){
    $crons = shell_exec('crontab -l 2>/dev/null');
    echo strpos($crons,'worker.php')!==false?"✅ Worker cron found\n":"⚠️ Worker cron NOT found — add it in cPanel!\n";
} else {
    echo "ℹ️ Cannot check cron from PHP — verify in cPanel\n";
}

// 6. Test API
echo "\n🔌 Testing visitor_ask API...\n";
$ctx = stream_context_create(['http'=>[
    'method'=>'POST',
    'header'=>'Content-Type: application/json',
    'content'=>json_encode(['question'=>'test']),
    'timeout'=>5
]]);
$base = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!='off'?'https':'http').'://'.$_SERVER['HTTP_HOST'];
$resp = @file_get_contents($base.'/api/visitor_ask.php',false,$ctx);
if($resp){
    $d = json_decode($resp,true);
    echo isset($d['error'])&&$d['error']==='missing_question'?"✅ API responding correctly\n":"ℹ️ API response: $resp\n";
} else {
    echo "⚠️ Could not reach API internally\n";
}

echo "\n=== Deploy check complete ===\n";
echo "\n⚠️  DELETE THIS FILE NOW: rm deploy.php\n";
echo "</pre>";
