<?php
/**
 * SonicPesa Diagnostics Script
 * Run this on your shared hosting to identify 500 errors and schema issues.
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';
require_once 'includes/db.php';

echo "<h1>SonicPesa Server Diagnostics</h1>";

// 1. Check Directory Permissions
echo "<h2>1. Directory Checks</h2>";
$dirs = ['uploads', 'assets/images/landing', 'templates', 'assets/images/avatars'];
foreach ($dirs as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }
    if (is_dir($dir)) {
        $writable = is_writable($dir) ? "✅ Writable" : "❌ NOT Writable";
        echo "<p>Directory <strong>$dir</strong>: $writable</p>";
    } else {
        echo "<p>Directory <strong>$dir</strong>: ❌ DOES NOT EXIST (and could not be created)</p>";
    }
}
$free_space = disk_free_space(".");
$total_space = disk_total_space(".");
echo "<p>Free Disk Space: " . round($free_space / (1024 * 1024 * 1024), 2) . " GB / " . round($total_space / (1024 * 1024 * 1024), 2) . " GB</p>";
if ($free_space < 500 * 1024 * 1024) {
    echo "<p style='color:red;'>⚠️ WARNING: Disk space is very low (less than 500MB). This can cause slow performance.</p>";
}

// 2. Check Database Schema
echo "<h2>2. Database Schema Checks</h2>";
try {
    // Check Users table
    $stmt = $pdo->query("DESCRIBE users");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $required_user_cols = ['api_key', 'api_secret', 'redirect_url', 'role', 'landing_page', 'webhook_token', 'profile_pic'];
    echo "<h3>Users Table:</h3><ul>";
    foreach ($required_user_cols as $col) {
        if (in_array($col, $columns)) {
            echo "<li>✅ Column <strong>$col</strong> exists.</li>";
        } else {
            echo "<li style='color:red;'>❌ Column <strong>$col</strong> is MISSING!</li>";
        }
    }
    echo "</ul>";

    // Check Site Settings table
    $stmt = $pdo->query("DESCRIBE site_settings");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $required_settings_cols = ['site_name', 'site_logo', 'site_favicon', 'footer_copy', 'footer_made_by', 'allow_registration', 'allow_uploads', 'allow_withdrawals', 'system_commission', 'min_withdrawal', 'system_notification'];
    echo "<h3>Site Settings Table:</h3><ul>";
    foreach ($required_settings_cols as $col) {
        if (in_array($col, $columns)) {
            echo "<li>✅ Column <strong>$col</strong> exists.</li>";
        } else {
            echo "<li style='color:red;'>❌ Column <strong>$col</strong> is MISSING!</li>";
        }
    }
    echo "</ul>";

    // Check System Notifications table
    try {
        $stmt = $pdo->query("DESCRIBE system_notifications");
        echo "<p>✅ Table <strong>system_notifications</strong> exists.</p>";
    } catch (Exception $e) {
        echo "<p style='color:red;'>❌ Table <strong>system_notifications</strong> is MISSING!</p>";
    }

    // Check System Root Domains table
    try {
        $stmt = $pdo->query("DESCRIBE system_root_domains");
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (in_array('user_id', $columns)) {
            echo "<p>✅ Column <strong>user_id</strong> exists in system_root_domains table.</p>";
        } else {
            echo "<p style='color:red;'>❌ Column <strong>user_id</strong> is MISSING in system_root_domains table!</p>";
        }
    } catch (Exception $e) {
        echo "<p style='color:red;'>❌ Table <strong>system_root_domains</strong> is MISSING!</p>";
    }

    // Check Transactions table
    try {
        $stmt = $pdo->query("DESCRIBE transactions");
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (in_array('method', $columns)) {
            echo "<p>✅ Column <strong>method</strong> exists in transactions table.</p>";
        } else {
            echo "<p style='color:red;'>❌ Column <strong>method</strong> is MISSING in transactions table!</p>";
        }
    } catch (Exception $e) {
        echo "<p style='color:red;'>❌ Table <strong>transactions</strong> is MISSING!</p>";
    }

    // Check Withdrawals table
    $stmt = $pdo->query("DESCRIBE withdrawals");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    if (in_array('withdrawal_id', $columns)) {
        echo "<p>✅ Column <strong>withdrawal_id</strong> exists in withdrawals table.</p>";
    } else {
        echo "<p style='color:red;'>❌ Column <strong>withdrawal_id</strong> is MISSING in withdrawals table!</p>";
    }

    // Check Videos table
    $stmt = $pdo->query("DESCRIBE videos");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $required_video_cols = ['id', 'user_id', 'title', 'price', 'video_url', 'thumbnail_url', 'position', 'fake_views'];
    echo "<h3>Videos Table:</h3><ul>";
    foreach ($required_video_cols as $col) {
        if (in_array($col, $columns)) {
            echo "<li>✅ Column <strong>$col</strong> exists.</li>";
        } else {
            echo "<li style='color:red;'>❌ Column <strong>$col</strong> is MISSING!</li>";
        }
    }
    echo "</ul>";

} catch (Exception $e) {
    echo "<p style='color:red;'>Database Error: " . $e->getMessage() . "</p>";
}

// 3. PHP Settings
echo "<h2>3. PHP Configuration (Upload Limits)</h2>";
echo "<ul>";
echo "<li>PHP Version: " . PHP_VERSION . "</li>";
echo "<li>Server IP Address: " . ($_SERVER['SERVER_ADDR'] ?? 'Unknown') . "</li>";
echo "<li>SITE_URL: " . (defined('SITE_URL') ? SITE_URL : 'NOT DEFINED') . "</li>";
echo "<li>upload_max_filesize: " . ini_get('upload_max_filesize') . " (Max file size for a single upload)</li>";
echo "<li>post_max_size: " . ini_get('post_max_size') . " (Max total size of POST data)</li>";
echo "<li>max_execution_time: " . ini_get('max_execution_time') . " seconds (Max script run time)</li>";
echo "<li>max_input_time: " . ini_get('max_input_time') . " seconds (Max time to parse input data)</li>";
echo "<li>memory_limit: " . ini_get('memory_limit') . "</li>";
echo "</ul>";

if (intval(ini_get('upload_max_filesize')) < 20) {
    echo "<p style='color:orange;'>⚠️ Your upload limit is very low. This may cause slow uploads or failures for large videos. Recommended: 100M+</p>";
}

// 4. API Accessibility Test
echo "<h2>4. API Accessibility Test</h2>";
$api_scripts = ['api/pay.php', 'api/ping.php', 'api/check_status.php'];
foreach ($api_scripts as $script) {
    if (file_exists($script)) {
        $perms = substr(sprintf('%o', fileperms($script)), -4);
        echo "<p>✅ File <strong>$script</strong> exists (Perms: $perms).</p>";
    } else {
        echo "<p style='color:red;'>❌ File <strong>$script</strong> DOES NOT EXIST!</p>";
    }
}
$url = (defined('SITE_URL') ? SITE_URL : '') . '/api/ping.php';
echo "<p>Test this URL in your browser: <a href='$url' target='_blank'>$url</a></p>";
echo "<p>If the link above gives a 404, your .htaccess is still blocking the api/ folder.</p>";

// 5. SonicPesa API Configuration
echo "<h2>5. SonicPesa API Configuration</h2>";
echo "<ul>";
echo "<li>SONICPESA_API_URL: " . (defined('SONICPESA_API_URL') ? SONICPESA_API_URL : '<span style="color:red">NOT DEFINED</span>') . "</li>";
$tokenSet = defined('SONICPESA_API_TOKEN') && SONICPESA_API_TOKEN !== 'YOUR_SONICPESA_API_TOKEN';
echo "<li>SONICPESA_API_TOKEN: " . ($tokenSet ? '✅ Set (' . strlen(SONICPESA_API_TOKEN) . ' chars)' : '<span style="color:orange">⚠️ Not configured yet</span>') . "</li>";
$secretSet = defined('SONICPESA_API_SECRET') && SONICPESA_API_SECRET !== 'YOUR_SONICPESA_API_SECRET';
echo "<li>SONICPESA_API_SECRET: " . ($secretSet ? '✅ Set' : '<span style="color:orange">⚠️ Not configured (needed for webhooks)</span>') . "</li>";
echo "</ul>";

echo "<p><strong>If you see MISSING columns above, please run <a href='alter_db.php'>alter_db.php</a> or re-run <a href='install.php'>install.php</a>.</strong></p>";
?>

