<?php
/**
 * Stock Validation Dashboard
 * Run daily/weekly to catch stock discrepancies early
 * Usage: php check_stock_health.php
 */

require_once 'config/config.php';
require_once 'core/StockUtilities.php';

$pdo = new PDO(
    "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
    DB_USER,
    DB_PASS
);

// Check if this is a web request or CLI
$isWeb = php_sapi_name() !== 'cli';

if ($isWeb) {
    header('Content-Type: application/json');
}

echo $isWeb ? json_encode(runValidation($pdo)) : runValidationCli($pdo);

function runValidation($pdo): array {
    $validator = new StockValidator($pdo);
    $results = $validator->validateAll();
    $discrepancies = $validator->getDiscrepancyReport();
    
    return [
        'timestamp' => date('Y-m-d H:i:s'),
        'summary' => $results,
        'discrepancies' => $discrepancies,
        'status' => $results['all_valid'] ? 'healthy' : 'issues_found'
    ];
}

function runValidationCli($pdo): string {
    $validator = new StockValidator($pdo);
    $results = $validator->validateAll();
    $discrepancies = $validator->getDiscrepancyReport();
    
    $output = "\n";
    $output .= "╔════════════════════════════════════════════════════════════╗\n";
    $output .= "║          STOCK HEALTH CHECK REPORT                         ║\n";
    $output .= "║          " . date('Y-m-d H:i:s') . "                                ║\n";
    $output .= "╚════════════════════════════════════════════════════════════╝\n\n";
    
    $output .= "📊 SUMMARY\n";
    $output .= "   Total Products:    " . $results['total_products'] . "\n";
    $output .= "   Valid Products:    " . $results['valid_products'] . "\n";
    $output .= "   Issues Found:      " . $results['issues_found'] . "\n";
    $output .= "   Status:            " . ($results['all_valid'] ? "✓ HEALTHY" : "⚠ ISSUES DETECTED") . "\n\n";
    
    if ($results['issues_found'] > 0) {
        $output .= "⚠ DISCREPANCIES DETECTED:\n";
        $output .= str_repeat("─", 60) . "\n";
        foreach ($discrepancies as $issue) {
            $difference = abs(($issue['stock_total'] ?? 0) - ($issue['movements_total'] ?? 0));
            $output .= "  SKU: " . $issue['sku'] . " | ";
            $output .= $issue['name'] . "\n";
            $output .= "    Stock Table: " . number_format($issue['stock_total'] ?? 0, 2) . "\n";
            $output .= "    Movements:   " . number_format($issue['movements_total'] ?? 0, 2) . "\n";
            $output .= "    Difference: " . number_format($difference, 2) . " boxes\n\n";
        }
        $output .= "🔧 ACTION REQUIRED:\n";
        $output .= "   Run: php run_global_stock_reconciliation.php\n";
    } else {
        $output .= "✓ All products are in sync!\n";
    }
    
    $output .= "\n" . str_repeat("═", 60) . "\n\n";
    
    return $output;
}
