<?php
session_start();
require_once 'config/db.php';

// Use $connection from config/db.php
$conn = $connection;

// Check connection
if (!$conn) {
    echo "❌ Database connection failed!<br>";
    exit;
}

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo "❌ Not authenticated as admin!<br>";
    echo "User ID: " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'Not set') . "<br>";
    echo "User Role: " . (isset($_SESSION['user_role']) ? $_SESSION['user_role'] : 'Not set') . "<br>";
    exit;
}

echo "✅ Authenticated as admin<br><br>";

// Create table
$create_table_sql = "CREATE TABLE IF NOT EXISTS team_members (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    designation VARCHAR(100) NOT NULL,
    image_path VARCHAR(255),
    twitter_url VARCHAR(255),
    linkedin_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_created (created_at)
)";

if ($conn->query($create_table_sql)) {
    echo "✅ Table created/verified<br>";
} else {
    echo "❌ Error creating table: " . $conn->error . "<br>";
    exit;
}

// Check count
$count_result = $conn->query("SELECT COUNT(*) as count FROM team_members");
$count_row = $count_result->fetch_assoc();

echo "📊 Current team members in database: " . $count_row['count'] . "<br><br>";

if ($count_row['count'] == 0) {
    echo "🔄 Initializing team members from team.html...<br><br>";
    
    // Parse team.html to extract team members
    $team_html_file = __DIR__ . '/team.html';
    
    if (!file_exists($team_html_file)) {
        echo "❌ team.html not found at: " . $team_html_file . "<br>";
        exit;
    }
    
    echo "✅ Found team.html<br>";
    
    $html_content = file_get_contents($team_html_file);
    echo "✅ Read " . strlen($html_content) . " bytes from team.html<br><br>";
    
    // Extract team members using regex pattern
    $pattern = '/<div class="col-md-6 col-xl-4">.*?<img src="([^"]+)"[^>]*alt="Team".*?<a href="team-details.html">([^<]+)<\/a><\/h3><span\s+class="team-desig">([^<]+)<\/span>/s';
    
    if (preg_match_all($pattern, $html_content, $matches)) {
        echo "✅ Found " . count($matches[1]) . " team members in HTML<br><br>";
        
        for ($i = 0; $i < count($matches[1]); $i++) {
            $image_path = $matches[1][$i];
            $name = $matches[2][$i];
            $designation = $matches[3][$i];
            $twitter_url = 'https://twitter.com/';
            $linkedin_url = 'https://linkedin.com/';
            
            echo "Adding: <strong>" . htmlspecialchars($name) . "</strong> - " . htmlspecialchars($designation) . " (" . htmlspecialchars($image_path) . ")<br>";
            
            $stmt = $conn->prepare("INSERT INTO team_members (name, designation, image_path, twitter_url, linkedin_url) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param('sssss', $name, $designation, $image_path, $twitter_url, $linkedin_url);
            
            if ($stmt->execute()) {
                echo "   ✅ Added<br>";
            } else {
                echo "   ❌ Error: " . $stmt->error . "<br>";
            }
            $stmt->close();
        }
        
        echo "<br>✅ Initialization complete!<br>";
    } else {
        echo "❌ Could not extract team members from HTML<br>";
        echo "Pattern used: " . $pattern . "<br>";
    }
} else {
    echo "✅ Team members already in database<br><br>";
    
    // Display current members
    $result = $conn->query("SELECT * FROM team_members ORDER BY created_at ASC");
    
    if ($result) {
        echo "<table border='1' cellpadding='10'>";
        echo "<tr><th>ID</th><th>Name</th><th>Designation</th><th>Image</th><th>Created</th></tr>";
        
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . htmlspecialchars($row['name']) . "</td>";
            echo "<td>" . htmlspecialchars($row['designation']) . "</td>";
            echo "<td>" . htmlspecialchars($row['image_path']) . "</td>";
            echo "<td>" . $row['created_at'] . "</td>";
            echo "</tr>";
        }
        
        echo "</table>";
    }
}

echo "<br><br><a href='admin-dashboard.php'>← Back to Admin Dashboard</a>";
?>
