#!/usr/bin/env php
<?php

/**
 * Performance Check Script
 * Run this to verify your production environment is optimized
 */

echo "\n╔════════════════════════════════════════════════════════════╗\n";
echo "║          INVENTINO POS - Performance Checker           ║\n";
echo "╚════════════════════════════════════════════════════════════╝\n\n";

$issues = [];
$warnings = [];
$passes = [];

// Check 1: APP_DEBUG
echo "Checking APP_DEBUG setting... ";
if (getenv('APP_DEBUG') === 'false' || getenv('APP_DEBUG') === '0') {
    echo "✅ PASS\n";
    $passes[] = "Debug mode is disabled";
} else {
    echo "❌ FAIL\n";
    $issues[] = "APP_DEBUG is enabled - Set APP_DEBUG=false in .env file";
}

// Check 2: APP_ENV
echo "Checking APP_ENV setting... ";
$env = getenv('APP_ENV') ?: 'local';
if ($env === 'production') {
    echo "✅ PASS\n";
    $passes[] = "Environment is set to production";
} else {
    echo "⚠️  WARNING\n";
    $warnings[] = "APP_ENV is set to '{$env}' - Consider setting to 'production'";
}

// Check 3: PHP Version
echo "Checking PHP version... ";
$phpVersion = PHP_VERSION;
if (version_compare($phpVersion, '8.1.0', '>=')) {
    echo "✅ PASS (PHP {$phpVersion})\n";
    $passes[] = "PHP version is up to date";
} else {
    echo "⚠️  WARNING (PHP {$phpVersion})\n";
    $warnings[] = "PHP version is below 8.1 - Consider upgrading";
}

// Check 4: OPcache
echo "Checking OPcache... ";
if (function_exists('opcache_get_status') && opcache_get_status() !== false) {
    $status = opcache_get_status();
    if ($status['opcache_enabled']) {
        echo "✅ PASS\n";
        $passes[] = "OPcache is enabled and running";
    } else {
        echo "❌ FAIL\n";
        $issues[] = "OPcache is installed but disabled - Enable in php.ini";
    }
} else {
    echo "❌ FAIL\n";
    $issues[] = "OPcache is not installed - Install and enable opcache extension";
}

// Check 5: Memory Limit
echo "Checking PHP memory limit... ";
$memoryLimit = ini_get('memory_limit');
$memoryBytes = return_bytes($memoryLimit);
if ($memoryBytes >= 256 * 1024 * 1024) {
    echo "✅ PASS ({$memoryLimit})\n";
    $passes[] = "Memory limit is adequate";
} else {
    echo "⚠️  WARNING ({$memoryLimit})\n";
    $warnings[] = "Memory limit is below 256M - Increase in php.ini";
}

// Check 6: Max Execution Time
echo "Checking max execution time... ";
$maxTime = ini_get('max_execution_time');
if ($maxTime >= 30) {
    echo "✅ PASS ({$maxTime}s)\n";
    $passes[] = "Max execution time is sufficient";
} else {
    echo "⚠️  WARNING ({$maxTime}s)\n";
    $warnings[] = "Max execution time is low - Increase to at least 30s";
}

// Check 7: Laravel Cache
echo "Checking Laravel cache... ";
if (file_exists(__DIR__ . '/bootstrap/cache/config.php')) {
    echo "✅ PASS\n";
    $passes[] = "Laravel configuration is cached";
} else {
    echo "❌ FAIL\n";
    $issues[] = "Laravel cache not found - Run 'php artisan optimize'";
}

// Check 8: Build Assets
echo "Checking build assets... ";
if (file_exists(__DIR__ . '/public/build/manifest.json')) {
    echo "✅ PASS\n";
    $passes[] = "Frontend assets are built";
} else {
    echo "❌ FAIL\n";
    $issues[] = "Build assets not found - Run 'npm run build'";
}

// Check 9: Storage Permissions
echo "Checking storage permissions... ";
if (is_writable(__DIR__ . '/storage')) {
    echo "✅ PASS\n";
    $passes[] = "Storage directory is writable";
} else {
    echo "❌ FAIL\n";
    $issues[] = "Storage directory is not writable - Check permissions";
}

// Check 10: MySQL Version (if connection available)
echo "Checking MySQL connection... ";
try {
    if (file_exists(__DIR__ . '/vendor/autoload.php')) {
        require __DIR__ . '/vendor/autoload.php';
        $app = require_once __DIR__ . '/bootstrap/app.php';
        $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
        $kernel->bootstrap();
        
        $pdo = DB::connection()->getPdo();
        $version = $pdo->query('SELECT VERSION()')->fetchColumn();
        echo "✅ PASS (MySQL {$version})\n";
        $passes[] = "Database connection is working";
    } else {
        echo "⚠️  SKIP\n";
        $warnings[] = "Could not check MySQL - Laravel not fully installed";
    }
} catch (Exception $e) {
    echo "❌ FAIL\n";
    $issues[] = "MySQL connection failed: " . $e->getMessage();
}

// Summary
echo "\n╔════════════════════════════════════════════════════════════╗\n";
echo "║                    RESULTS SUMMARY                         ║\n";
echo "╚════════════════════════════════════════════════════════════╝\n\n";

echo "✅ Passed: " . count($passes) . "\n";
echo "⚠️  Warnings: " . count($warnings) . "\n";
echo "❌ Failed: " . count($issues) . "\n\n";

if (!empty($issues)) {
    echo "🔴 CRITICAL ISSUES (Fix immediately):\n";
    echo "═══════════════════════════════════════\n";
    foreach ($issues as $i => $issue) {
        echo ($i + 1) . ". " . $issue . "\n";
    }
    echo "\n";
}

if (!empty($warnings)) {
    echo "⚠️  WARNINGS (Recommended to fix):\n";
    echo "═══════════════════════════════════════\n";
    foreach ($warnings as $i => $warning) {
        echo ($i + 1) . ". " . $warning . "\n";
    }
    echo "\n";
}

if (empty($issues) && empty($warnings)) {
    echo "🎉 PERFECT! Your application is fully optimized!\n\n";
} elseif (empty($issues)) {
    echo "✅ Good! No critical issues found. Address warnings when possible.\n\n";
} else {
    echo "❌ Action Required! Please fix the critical issues listed above.\n\n";
}

echo "📖 For detailed optimization guide, see: PERFORMANCE_OPTIMIZATION.md\n\n";

// Helper function
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $val = (int)$val;
    switch($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

exit(count($issues) > 0 ? 1 : 0);
