<?php
/**
 * CMS Features Testing Script
 * Tests all CMS functionality and creates sample data
 */

// Database configuration
$host = 'localhost';
$dbname = 'obgyn_research_platform';
$username = 'obgyn_research_platform_user';
$password = '2UFAT605IQCLmyyd';

echo "===========================================\n";
echo "CMS Features Testing Script\n";
echo "===========================================\n\n";

$testResults = [];
$passCount = 0;
$failCount = 0;

function testResult($testName, $passed, $message = '') {
    global $testResults, $passCount, $failCount;
    
    $status = $passed ? '✓ PASS' : '✗ FAIL';
    $testResults[] = [
        'name' => $testName,
        'passed' => $passed,
        'message' => $message
    ];
    
    if ($passed) {
        $passCount++;
        echo "✓ $testName\n";
    } else {
        $failCount++;
        echo "✗ $testName: $message\n";
    }
    
    if ($message && $passed) {
        echo "  → $message\n";
    }
}

try {
    // Connect to database
    echo "Connecting to database...\n";
    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    
    $pdo = new PDO($dsn, $username, $password, $options);
    testResult("Database Connection", true, "Connected successfully");
    echo "\n";
    
    // Test 1: Check if CMS tables exist
    echo "Testing CMS Tables...\n";
    $requiredTables = [
        'cms_pages', 'cms_posts', 'cms_menus', 'cms_menu_items',
        'cms_media', 'cms_widgets', 'cms_hero_sections', 'cms_features',
        'cms_testimonials', 'cms_stats', 'cms_sliders', 'cms_slider_items',
        'cms_team_members', 'email_templates'
    ];
    
    $stmt = $pdo->query("SHOW TABLES");
    $existingTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    foreach ($requiredTables as $table) {
        $exists = in_array($table, $existingTables);
        testResult("Table: $table", $exists, $exists ? "Exists" : "Missing");
    }
    echo "\n";
    
    // Test 2: Check email templates
    echo "Testing Email Templates...\n";
    $stmt = $pdo->query("SELECT COUNT(*) FROM email_templates");
    $templateCount = $stmt->fetchColumn();
    testResult("Email Templates", $templateCount >= 6, "Found $templateCount templates");
    echo "\n";
    
    // Test 3: Check CMS settings
    echo "Testing CMS Settings...\n";
    $stmt = $pdo->query("SELECT COUNT(*) FROM settings WHERE category = 'cms'");
    $settingsCount = $stmt->fetchColumn();
    testResult("CMS Settings", $settingsCount >= 10, "Found $settingsCount settings");
    echo "\n";
    
    // Test 4: Check if admin user exists
    echo "Testing Admin User...\n";
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE role_id = 1");
    $stmt->execute();
    $adminCount = $stmt->fetchColumn();
    testResult("Admin User Exists", $adminCount > 0, "Found $adminCount admin user(s)");
    echo "\n";
    
    // Test 5: Create sample CMS page
    echo "Testing Page Creation...\n";
    try {
        // Get admin user ID
        $stmt = $pdo->query("SELECT id FROM users WHERE role_id = 1 LIMIT 1");
        $adminId = $stmt->fetchColumn();
        
        if ($adminId) {
            $stmt = $pdo->prepare("
                INSERT INTO cms_pages (
                    title, slug, content, status, language, created_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $stmt->execute([
                'Test Page - CMS Testing',
                'test-page-cms-testing',
                '<h1>Welcome to Test Page</h1><p>This is a test page created by the CMS testing script.</p>',
                'published',
                'en',
                $adminId
            ]);
            
            $pageId = $pdo->lastInsertId();
            testResult("Create CMS Page", true, "Created page ID: $pageId");
            
            // Test reading the page
            $stmt = $pdo->prepare("SELECT * FROM cms_pages WHERE id = ?");
            $stmt->execute([$pageId]);
            $page = $stmt->fetch();
            testResult("Read CMS Page", $page !== false, "Retrieved page: {$page['title']}");
            
            // Test updating the page
            $stmt = $pdo->prepare("UPDATE cms_pages SET title = ? WHERE id = ?");
            $stmt->execute(['Test Page - Updated', $pageId]);
            testResult("Update CMS Page", true, "Updated page title");
            
            // Test deleting the page
            $stmt = $pdo->prepare("DELETE FROM cms_pages WHERE id = ?");
            $stmt->execute([$pageId]);
            testResult("Delete CMS Page", true, "Deleted test page");
        } else {
            testResult("Create CMS Page", false, "No admin user found");
        }
    } catch (Exception $e) {
        testResult("Page CRUD Operations", false, $e->getMessage());
    }
    echo "\n";
    
    // Test 6: Create sample data for testing
    echo "Creating Sample Data...\n";
    
    if ($adminId) {
        // Create sample pages
        $samplePages = [
            ['About Us', 'about-us', '<h1>About Us</h1><p>Learn more about our platform.</p>'],
            ['Contact', 'contact', '<h1>Contact Us</h1><p>Get in touch with us.</p>'],
            ['Privacy Policy', 'privacy-policy', '<h1>Privacy Policy</h1><p>Our privacy policy.</p>'],
            ['Terms of Service', 'terms-of-service', '<h1>Terms of Service</h1><p>Terms and conditions.</p>'],
        ];
        
        foreach ($samplePages as $pageData) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO cms_pages (
                        title, slug, content, status, language, created_by, created_at
                    ) VALUES (?, ?, ?, 'published', 'en', ?, NOW())
                ");
                $stmt->execute([$pageData[0], $pageData[1], $pageData[2], $adminId]);
                testResult("Sample Page: {$pageData[0]}", true, "Created");
            } catch (Exception $e) {
                if (strpos($e->getMessage(), 'Duplicate') !== false) {
                    testResult("Sample Page: {$pageData[0]}", true, "Already exists");
                } else {
                    testResult("Sample Page: {$pageData[0]}", false, $e->getMessage());
                }
            }
        }
        
        // Create sample features
        $sampleFeatures = [
            ['Research Collaboration', 'fas fa-users', 'Connect with researchers worldwide'],
            ['Data Security', 'fas fa-lock', 'Your data is secure and encrypted'],
            ['Easy Publishing', 'fas fa-book', 'Publish your research easily'],
            ['Analytics', 'fas fa-chart-line', 'Track your research impact'],
        ];
        
        foreach ($sampleFeatures as $featureData) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO cms_features (
                        title, icon, description, status, created_at
                    ) VALUES (?, ?, ?, 'active', NOW())
                ");
                $stmt->execute($featureData);
                testResult("Sample Feature: {$featureData[0]}", true, "Created");
            } catch (Exception $e) {
                testResult("Sample Feature: {$featureData[0]}", false, $e->getMessage());
            }
        }
        
        // Create sample stats
        $sampleStats = [
            ['Active Researchers', '1,234', '+', 'fas fa-users', '#007bff'],
            ['Published Studies', '567', '', 'fas fa-flask', '#28a745'],
            ['Collaborations', '890', '', 'fas fa-handshake', '#ffc107'],
            ['Publications', '2,345', '+', 'fas fa-book', '#dc3545'],
        ];
        
        foreach ($sampleStats as $statData) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO cms_stats (
                        label, value, suffix, icon, color, status, created_at
                    ) VALUES (?, ?, ?, ?, ?, 'active', NOW())
                ");
                $stmt->execute($statData);
                testResult("Sample Stat: {$statData[0]}", true, "Created");
            } catch (Exception $e) {
                testResult("Sample Stat: {$statData[0]}", false, $e->getMessage());
            }
        }
        
        // Create sample testimonials
        $sampleTestimonials = [
            ['Dr. Sarah Johnson', 'Chief Researcher', 'University Hospital', 'This platform has revolutionized how we collaborate on research projects.', 5],
            ['Dr. Michael Chen', 'Professor', 'Medical Institute', 'An invaluable tool for the OBGYN research community.', 5],
            ['Dr. Emily Williams', 'Research Director', 'Health Center', 'The best platform for sharing and discovering research.', 4],
        ];
        
        foreach ($sampleTestimonials as $testimonialData) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO cms_testimonials (
                        name, title, company, testimonial, rating, status, created_at
                    ) VALUES (?, ?, ?, ?, ?, 'active', NOW())
                ");
                $stmt->execute($testimonialData);
                testResult("Sample Testimonial: {$testimonialData[0]}", true, "Created");
            } catch (Exception $e) {
                testResult("Sample Testimonial: {$testimonialData[0]}", false, $e->getMessage());
            }
        }
    }
    
    echo "\n";
    
    // Test 7: Check file permissions
    echo "Testing File Permissions...\n";
    $uploadDirs = [
        '../assets/uploads',
        '../assets/uploads/profiles',
        '../assets/uploads/documents',
        '../assets/uploads/studies'
    ];
    
    foreach ($uploadDirs as $dir) {
        $writable = is_writable($dir);
        testResult("Directory Writable: $dir", $writable, $writable ? "Writable" : "Not writable");
    }
    echo "\n";
    
    // Summary
    echo "===========================================\n";
    echo "Test Summary\n";
    echo "===========================================\n";
    echo "Total Tests: " . ($passCount + $failCount) . "\n";
    echo "Passed: $passCount ✓\n";
    echo "Failed: $failCount ✗\n";
    echo "Success Rate: " . round(($passCount / ($passCount + $failCount)) * 100, 2) . "%\n";
    echo "===========================================\n\n";
    
    if ($failCount === 0) {
        echo "🎉 All tests passed! CMS is ready to use.\n\n";
        echo "Next Steps:\n";
        echo "1. Login to admin panel: http://localhost/obgyn-research-platform/admin/\n";
        echo "2. Navigate to CMS → Pages\n";
        echo "3. You should see 4 sample pages created\n";
        echo "4. Try creating, editing, and deleting pages\n";
    } else {
        echo "⚠ Some tests failed. Please review the errors above.\n";
    }
    
} catch (PDOException $e) {
    echo "\n✗ Database Error: " . $e->getMessage() . "\n";
    echo "\nPlease check:\n";
    echo "1. Database credentials are correct\n";
    echo "2. Database exists\n";
    echo "3. Run cms_migration.sql first\n";
    echo "4. Run create_admin_user.php to create admin user\n";
    exit(1);
} catch (Exception $e) {
    echo "\n✗ Error: " . $e->getMessage() . "\n";
    exit(1);
}
