<?php
/**
 * ============================================================================
 * GROUPS SYSTEM - INSTALLATION HELPER
 * ============================================================================
 * Run this file once to verify and fix installation issues
 * Access: http://localhost/aims/groups/install-helper.php
 */

// Check if Group.php exists
$groupClassPath = __DIR__ . '/../classes/Group.php';
$ajaxPath = __DIR__ . '/ajax/group-actions.php';

echo "<!DOCTYPE html>
<html>
<head>
    <title>Groups System - Installation Helper</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
        .success { color: green; padding: 10px; background: #d4edda; border-radius: 5px; margin: 10px 0; }
        .error { color: red; padding: 10px; background: #f8d7da; border-radius: 5px; margin: 10px 0; }
        .info { color: blue; padding: 10px; background: #d1ecf1; border-radius: 5px; margin: 10px 0; }
        pre { background: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; }
        .step { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>🚀 Groups System - Installation Helper</h1>
    <p>This helper will check your installation and provide fixes.</p>";

// Step 1: Check Group.php
echo "<div class='step'>
    <h2>Step 1: Checking Group.php Class File</h2>";

if (file_exists($groupClassPath)) {
    echo "<div class='success'>✓ Group.php found at: {$groupClassPath}</div>";
    
    // Check if it's readable
    if (is_readable($groupClassPath)) {
        echo "<div class='success'>✓ Group.php is readable</div>";
        
        // Try to include it
        try {
            require_once $groupClassPath;
            echo "<div class='success'>✓ Group.php loaded successfully</div>";
            
            // Check if class exists
            if (class_exists('App\Group')) {
                echo "<div class='success'>✓ App\\Group class is available</div>";
            } else {
                echo "<div class='error'>✗ App\\Group class not found after loading file</div>";
            }
        } catch (Exception $e) {
            echo "<div class='error'>✗ Error loading Group.php: " . $e->getMessage() . "</div>";
        }
    } else {
        echo "<div class='error'>✗ Group.php is not readable. Check file permissions.</div>";
    }
} else {
    echo "<div class='error'>✗ Group.php NOT found at: {$groupClassPath}</div>";
    echo "<div class='info'>
        <strong>To fix:</strong>
        <ol>
            <li>Download the Group.php file from the outputs</li>
            <li>Copy it to: <code>C:\\Server\\xampp\\htdocs\\aims\\classes\\Group.php</code></li>
            <li>Refresh this page</li>
        </ol>
    </div>";
}

echo "</div>";

// Step 2: Check AJAX handler
echo "<div class='step'>
    <h2>Step 2: Checking AJAX Handler</h2>";

if (file_exists($ajaxPath)) {
    echo "<div class='success'>✓ group-actions.php found</div>";
} else {
    echo "<div class='error'>✗ group-actions.php NOT found at: {$ajaxPath}</div>";
    
    // Create ajax directory if it doesn't exist
    $ajaxDir = __DIR__ . '/ajax';
    if (!is_dir($ajaxDir)) {
        echo "<div class='info'>Creating ajax directory...</div>";
        if (mkdir($ajaxDir, 0755, true)) {
            echo "<div class='success'>✓ Ajax directory created</div>";
        } else {
            echo "<div class='error'>✗ Failed to create ajax directory</div>";
        }
    }
    
    echo "<div class='info'>
        <strong>To fix:</strong>
        <ol>
            <li>Download group-actions.php from the outputs</li>
            <li>Create folder: <code>C:\\Server\\xampp\\htdocs\\aims\\groups\\ajax\\</code></li>
            <li>Copy group-actions.php to that folder</li>
            <li>Refresh this page</li>
        </ol>
    </div>";
}

echo "</div>";

// Step 3: Check database table
echo "<div class='step'>
    <h2>Step 3: Checking Database Tables</h2>";

try {
    define('AIMS_ACCESS', true);
    require_once __DIR__ . '/../config/config.php';
    
    $database = new \App\Database();
    $db = $database->getConnection();
    
    // Check group_post_likes table
    $sql = "SHOW TABLES LIKE 'group_post_likes'";
    $stmt = $db->query($sql);
    $table = $stmt->fetch();
    
    if ($table) {
        echo "<div class='success'>✓ group_post_likes table exists</div>";
    } else {
        echo "<div class='error'>✗ group_post_likes table NOT found</div>";
        echo "<div class='info'>
            <strong>To fix:</strong>
            <ol>
                <li>Open phpMyAdmin</li>
                <li>Select your 'aims_db' database</li>
                <li>Click SQL tab</li>
                <li>Run the SQL from add_group_post_likes.sql file</li>
            </ol>
            <strong>SQL to run:</strong>
            <pre>CREATE TABLE IF NOT EXISTS `group_post_likes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_post_like` (`post_id`,`user_id`),
  KEY `idx_post` (`post_id`),
  KEY `idx_user` (`user_id`),
  CONSTRAINT `group_post_likes_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `group_posts` (`id`) ON DELETE CASCADE,
  CONSTRAINT `group_post_likes_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;</pre>
        </div>";
    }
    
    // Check other required tables
    $requiredTables = ['groups', 'group_members', 'group_posts', 'group_post_comments'];
    foreach ($requiredTables as $tableName) {
        $sql = "SHOW TABLES LIKE '{$tableName}'";
        $stmt = $db->query($sql);
        $table = $stmt->fetch();
        
        if ($table) {
            echo "<div class='success'>✓ {$tableName} table exists</div>";
        } else {
            echo "<div class='error'>✗ {$tableName} table NOT found</div>";
        }
    }
    
} catch (Exception $e) {
    echo "<div class='error'>✗ Database check failed: " . $e->getMessage() . "</div>";
}

echo "</div>";

// Step 4: Final check
echo "<div class='step'>
    <h2>Step 4: Final Verification</h2>";

$allGood = file_exists($groupClassPath) && 
           file_exists($ajaxPath) && 
           class_exists('App\Group', false);

if ($allGood) {
    echo "<div class='success'>
        <h3>✓ Installation Complete!</h3>
        <p>All components are properly installed. You can now:</p>
        <ul>
            <li><a href='index.php'>View Groups List</a></li>
            <li><a href='create.php'>Create a New Group</a></li>
        </ul>
        <p><strong>Important:</strong> Delete this install-helper.php file for security.</p>
    </div>";
} else {
    echo "<div class='error'>
        <h3>⚠ Installation Incomplete</h3>
        <p>Please fix the errors above and refresh this page.</p>
    </div>";
}

echo "</div>";

echo "<hr>
<h2>📁 Expected File Structure</h2>
<pre>
C:\\Server\\xampp\\htdocs\\aims\\
├── classes/
│   └── Group.php              ← Must exist
├── groups/
│   ├── ajax/
│   │   └── group-actions.php  ← Must exist
│   ├── index.php
│   ├── create.php
│   ├── view.php               ← Updated file
│   └── install-helper.php     ← This file (delete after installation)
└── config/
    └── config.php
</pre>";

echo "</body>
</html>";
?>