<?php
/**
 * Deployment Validation Script
 * Run this after uploading to cPanel to verify everything is working
 * 
 * Access via: yourdomain.com/validate_deployment.php
 * 
 * IMPORTANT: Delete this file after validation!
 */

// Detect web base path
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
if (strpos($scriptName, '/emporio-sport/') === 0 || $scriptName === '/emporio-sport' || $scriptName === '/emporio-sport/index.php') {
    $basePath = '/emporio-sport';
} else {
    $basePath = '';
}

$results = [];
$allPassed = true;

// Test 1: File structure
$results['file_structure'] = [
    'name' => '1. File Structure',
    'checks' => []
];

$requiredFiles = [
    'data/products.json',
    'data/categories.json',
    'data/pages.json',
    'helpers/navigation_helper.php',
    'config/image_config.php',
    '.htaccess'
];

foreach ($requiredFiles as $file) {
    $path = __DIR__ . '/' . $file;
    $exists = file_exists($path);
    $results['file_structure']['checks'][] = [
        'file' => $file,
        'status' => $exists ? 'PASS' : 'FAIL',
        'message' => $exists ? "File exists" : "File missing!"
    ];
    if (!$exists) $allPassed = false;
}

// Test 2: Image folders
$results['image_folders'] = [
    'name' => '2. Image Folders',
    'checks' => []
];

$imageFolders = [
    'pics_ecom',
    'sport-pics'
];

foreach ($imageFolders as $folder) {
    $path = __DIR__ . '/' . $folder;
    $exists = is_dir($path);
    $readable = $exists && is_readable($path);
    $results['image_folders']['checks'][] = [
        'folder' => $folder,
        'status' => ($exists && $readable) ? 'PASS' : 'FAIL',
        'message' => $exists ? ($readable ? "Folder readable" : "Folder not readable (permission issue)") : "Folder missing!"
    ];
    if (!($exists && $readable)) $allPassed = false;
}

// Test 3: JSON Files validity
$results['json_files'] = [
    'name' => '3. JSON Files Validity',
    'checks' => []
];

$jsonFiles = [
    'data/products.json' => 'Products',
    'data/categories.json' => 'Categories',
    'data/pages.json' => 'Pages'
];

foreach ($jsonFiles as $file => $label) {
    $path = __DIR__ . '/' . $file;
    $valid = false;
    $message = '';
    
    if (file_exists($path)) {
        $content = @file_get_contents($path);
        $decoded = @json_decode($content, true);
        if ($decoded !== null) {
            $valid = true;
            $count = count($decoded);
            $message = "Valid JSON, $count items";
        } else {
            $message = "Invalid JSON syntax: " . json_last_error_msg();
        }
    } else {
        $message = "File not found";
    }
    
    $results['json_files']['checks'][] = [
        'file' => $label,
        'status' => $valid ? 'PASS' : 'FAIL',
        'message' => $message
    ];
    if (!$valid) $allPassed = false;
}

// Test 4: Pages Navigation
$results['navigation'] = [
    'name' => '4. Pages Navigation',
    'checks' => []
];

$pagesFile = __DIR__ . '/data/pages.json';
$pagesValid = false;
$featuredCount = 0;
$totalCount = 0;

if (file_exists($pagesFile)) {
    $pages = @json_decode(file_get_contents($pagesFile), true);
    if (is_array($pages)) {
        $totalCount = count($pages);
        $pagesValid = true;
        
        foreach ($pages as $page) {
            if (!empty($page['is_featured'])) {
                $featuredCount++;
            }
        }
    }
}

$results['navigation']['checks'][] = [
    'check' => 'Pages loaded',
    'status' => $pagesValid ? 'PASS' : 'FAIL',
    'message' => $pagesValid ? "Found $totalCount pages ($featuredCount featured)" : "Pages not loading"
];

if (!$pagesValid) $allPassed = false;

// Test 5: Products Data
$results['products'] = [
    'name' => '5. Products Data',
    'checks' => []
];

$productsFile = __DIR__ . '/data/products.json';
$productsValid = false;
$productCount = 0;
$productsWithImages = 0;

if (file_exists($productsFile)) {
    $products = @json_decode(file_get_contents($productsFile), true);
    if (is_array($products)) {
        $productCount = count($products);
        $productsValid = true;
        
        foreach ($products as $product) {
            if (!empty($product['image'])) {
                $productsWithImages++;
            }
        }
    }
}

$results['products']['checks'][] = [
    'check' => 'Products loaded',
    'status' => $productsValid ? 'PASS' : 'FAIL',
    'message' => $productsValid ? "Found $productCount products, $productsWithImages with images" : "Products not loading"
];

if (!$productsValid) $allPassed = false;

// Test 6: Image Paths
$results['image_paths'] = [
    'name' => '6. Sample Image Paths',
    'checks' => []
];

require_once __DIR__ . '/config/image_config.php';

// Test image path function
$testImages = [
    'tennis.jpg',
    'sport-pics/soccer/calcio.jpg',
    'pics_ecom/tennis.jpg'
];

foreach ($testImages as $testImg) {
    $imagePath = getImageForSection($testImg);
    $results['image_paths']['checks'][] = [
        'input' => $testImg,
        'output' => $imagePath,
        'status' => 'INFO'
    ];
}

// Test 7: Web Base Path Detection
$results['web_base'] = [
    'name' => '7. Web Base Path Detection',
    'checks' => []
];

$webBasePath = getWebBasePath();
$results['web_base']['checks'][] = [
    'check' => 'Detected base path',
    'status' => 'INFO',
    'message' => "WEB_BASE_PATH = '$webBasePath'"
];

if ($basePath !== $webBasePath) {
    $results['web_base']['checks'][] = [
        'check' => 'Path consistency',
        'status' => 'WARN',
        'message' => "Script detected: '$basePath', getWebBasePath(): '$webBasePath'"
    ];
}

// Test 8: Database Connection (optional)
$results['database'] = [
    'name' => '8. Database Connection (Optional)',
    'checks' => []
];

// Try to load database config
$dbConfigPath = __DIR__ . '/config/db_config.php';
if (file_exists($dbConfigPath)) {
    require_once $dbConfigPath;
    
    if (isset($conn) && $conn) {
        $dbStatus = 'Connected';
        $status = 'PASS';
    } else {
        $dbStatus = 'Not connected (using JSON fallback)';
        $status = 'INFO';
    }
} else {
    $dbStatus = 'No DB config file';
    $status = 'INFO';
}

$results['database']['checks'][] = [
    'check' => 'Database',
    'status' => $status,
    'message' => $dbStatus
];

// Test 9: Key PHP Features
$results['php_features'] = [
    'name' => '9. PHP Features',
    'checks' => []
];

$features = [
    'json_decode' => function_exists('json_decode'),
    'file_get_contents' => function_exists('file_get_contents'),
    'file_exists' => function_exists('file_exists'),
    'is_readable' => function_exists('is_readable'),
    'session_start' => function_exists('session_start'),
];

foreach ($features as $feature => $exists) {
    $results['php_features']['checks'][] = [
        'feature' => $feature,
        'status' => $exists ? 'PASS' : 'FAIL',
        'message' => $exists ? 'Available' : 'Not available'
    ];
    if (!$exists) $allPassed = false;
}

// Test 10: Navigation Helper
$results['nav_helper'] = [
    'name' => '10. Navigation Helper',
    'checks' => []
];

require_once __DIR__ . '/helpers/navigation_helper.php';

if (class_exists('NavigationHelper')) {
    $featured = NavigationHelper::getFeaturedPages();
    $all = NavigationHelper::getAllPages();
    
    $results['nav_helper']['checks'][] = [
        'check' => 'getFeaturedPages()',
        'status' => !empty($featured) ? 'PASS' : 'INFO',
        'message' => "Found " . count($featured) . " featured pages"
    ];
    
    $results['nav_helper']['checks'][] = [
        'check' => 'getAllPages()',
        'status' => !empty($all) ? 'PASS' : 'INFO',
        'message' => "Found " . count($all) . " total pages"
    ];
} else {
    $results['nav_helper']['checks'][] = [
        'check' => 'NavigationHelper class',
        'status' => 'FAIL',
        'message' => 'Class not found'
    ];
    $allPassed = false;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Deployment Validation - Emporio Sport</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .status-banner {
            padding: 20px 30px;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
        }
        
        .status-banner.pass {
            background: #d4edda;
            color: #155724;
            border-bottom: 3px solid #28a745;
        }
        
        .status-banner.fail {
            background: #f8d7da;
            color: #721c24;
            border-bottom: 3px solid #dc3545;
        }
        
        .content {
            padding: 30px;
        }
        
        .test-section {
            margin-bottom: 30px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .test-section-title {
            background: #f5f5f5;
            padding: 15px 20px;
            font-weight: bold;
            font-size: 16px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .test-checks {
            padding: 15px 0;
        }
        
        .check {
            padding: 12px 20px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .check:last-child {
            border-bottom: none;
        }
        
        .check-left {
            flex: 1;
        }
        
        .check-label {
            font-weight: 500;
            color: #333;
        }
        
        .check-message {
            font-size: 13px;
            color: #666;
            margin-top: 3px;
        }
        
        .check-status {
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .status-pass {
            background: #d4edda;
            color: #155724;
        }
        
        .status-fail {
            background: #f8d7da;
            color: #721c24;
        }
        
        .status-info {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .status-warn {
            background: #fff3cd;
            color: #856404;
        }
        
        .footer {
            background: #f5f5f5;
            padding: 20px 30px;
            text-align: center;
            font-size: 13px;
            color: #666;
            border-top: 1px solid #e0e0e0;
        }
        
        .warning-box {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #856404;
        }
        
        .success-box {
            background: #d4edda;
            border: 1px solid #28a745;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #155724;
        }
        
        .code {
            background: #f4f4f4;
            padding: 8px 12px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        
        @media (max-width: 768px) {
            .header h1 {
                font-size: 22px;
            }
            
            .check {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .check-status {
                margin-top: 10px;
                align-self: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 Deployment Validation</h1>
            <p>Emporio Sport Website Status Check</p>
        </div>
        
        <div class="status-banner <?php echo $allPassed ? 'pass' : 'fail'; ?>">
            <?php echo $allPassed ? '✓ All critical checks PASSED' : '✗ Some checks FAILED - see details below'; ?>
        </div>
        
        <div class="content">
            <?php if (!$allPassed): ?>
            <div class="warning-box">
                <strong>⚠️ Action Required:</strong> Some checks failed. Please review the errors below and take corrective action before proceeding to production.
            </div>
            <?php else: ?>
            <div class="success-box">
                <strong>✓ Great News!</strong> All critical checks passed. Your website is ready for deployment!
            </div>
            <?php endif; ?>
            
            <?php foreach ($results as $sectionKey => $section): ?>
            <div class="test-section">
                <div class="test-section-title">
                    <?php echo $section['name']; ?>
                    <span style="font-size: 12px; font-weight: normal;">
                        (<?php echo count(array_filter($section['checks'], function($c) { return $c['status'] === 'PASS'; })); ?>/<?php echo count(array_filter($section['checks'], function($c) { return $c['status'] === 'PASS' || $c['status'] === 'FAIL'; })); ?> checks passed)
                    </span>
                </div>
                <div class="test-checks">
                    <?php foreach ($section['checks'] as $check): ?>
                    <div class="check">
                        <div class="check-left">
                            <div class="check-label">
                                <?php echo htmlspecialchars($check['file'] ?? $check['folder'] ?? $check['check'] ?? $check['feature'] ?? $check['input'] ?? $check['check'] ?? 'Unknown'); ?>
                            </div>
                            <div class="check-message">
                                <?php echo htmlspecialchars($check['message'] ?? $check['output'] ?? ''); ?>
                            </div>
                        </div>
                        <span class="check-status status-<?php echo strtolower($check['status']); ?>">
                            <?php echo $check['status']; ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>
            
            <div style="margin-top: 30px; padding: 20px; background: #f9f9f9; border-radius: 8px;">
                <h3 style="margin-bottom: 10px;">📝 Next Steps:</h3>
                <ol style="margin-left: 20px; line-height: 1.8;">
                    <li>If all checks passed: Proceed to test the website in your browser</li>
                    <li>Visit homepage: <span class="code"><?php echo htmlspecialchars($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $basePath . '/index.php'); ?></span></li>
                    <li>Visit shop: <span class="code"><?php echo htmlspecialchars($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $basePath . '/shop.php'); ?></span></li>
                    <li>Test navigation dropdown (click "MORE" in header)</li>
                    <li>Test shop filters and pagination</li>
                    <li><strong>Delete this validation script after testing:</strong> <span class="code">validate_deployment.php</span></li>
                </ol>
            </div>
        </div>
        
        <div class="footer">
            <p>System Information:</p>
            <p>PHP Version: <?php echo phpversion(); ?> | Server: <?php echo htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'); ?> | Detected Base Path: <span class="code"><?php echo htmlspecialchars($basePath ?: '/'); ?></span></p>
        </div>
    </div>
</body>
</html>
