Path : /home/vishqocm/pcib.in/admin/database/
File Upload :
Current File : //home/vishqocm/pcib.in/admin/database/fix_missing_columns.php

<?php
// Start session if not already started
if (session_status() === PHP_SESSION_INACTIVE) {
    session_start();
}

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director')) {
    $_SESSION['error_message'] = "Access denied. You must be logged in as an administrator.";
    header('Location: ../login.php');
    exit;
}

// Include database configuration
require_once 'db_config.php';

// Initialize messages array
$messages = [
    'success' => [],
    'error' => [],
    'info' => []
];

/**
 * Check if a column exists in a table and add it if it doesn't
 * 
 * @param mysqli $conn Database connection
 * @param string $table Table name
 * @param string $column Column name
 * @param string $definition Column definition (e.g., "VARCHAR(255) DEFAULT NULL")
 * @return bool True if column exists or was added successfully, false otherwise
 */
function check_and_add_column($conn, $table, $column, $definition) {
    global $messages;
    
    // Check if table exists
    $table_check = $conn->query("SHOW TABLES LIKE '$table'");
    if ($table_check->num_rows === 0) {
        $messages['info'][] = "Table '$table' does not exist in the database.";
        return false;
    }
    
    // Check if column exists
    $column_check = $conn->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
    if ($column_check->num_rows > 0) {
        $messages['info'][] = "Column '$column' already exists in table '$table'.";
        return true;
    }
    
    // Add column if it doesn't exist
    $add_column = $conn->query("ALTER TABLE `$table` ADD COLUMN `$column` $definition");
    if ($add_column) {
        $messages['success'][] = "Successfully added column '$column' to table '$table'.";
        return true;
    } else {
        $messages['error'][] = "Failed to add column '$column' to table '$table': " . $conn->error;
        return false;
    }
}

// Page title
$page_title = "Database Fix - Missing Columns";

// Set a page header that doesn't rely on including other files
echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . $page_title . '</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { padding-top: 20px; }
        .message-box { margin-bottom: 20px; }
        .fix-item { margin-bottom: 15px; padding: 15px; border-radius: 5px; background-color: #f8f9fa; }
        .fix-item h5 { margin-top: 0; }
        .fix-status { margin-top: 10px; }
        .success-box { background-color: #d4edda; border-left: 5px solid #28a745; }
        .error-box { background-color: #f8d7da; border-left: 5px solid #dc3545; }
        .info-box { background-color: #d1ecf1; border-left: 5px solid #17a2b8; }
        .navigation { margin-top: 30px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>' . $page_title . '</h1>
        <p class="lead">This script will check for and fix missing columns in your database tables.</p>';

// 1. Check 'designation' column in 'users' table
echo '<div class="fix-item">
        <h5><i class="fas fa-database"></i> Checking \'designation\' column in \'users\' table</h5>';

$users_table_exists = $conn->query("SHOW TABLES LIKE 'users'")->num_rows > 0;
if ($users_table_exists) {
    check_and_add_column($conn, 'users', 'designation', 'VARCHAR(255) DEFAULT NULL');
    
    // Also check for other instructor-specific columns
    check_and_add_column($conn, 'users', 'expertise', 'TEXT DEFAULT NULL');
    check_and_add_column($conn, 'users', 'social_links', 'TEXT DEFAULT NULL');
} else {
    $messages['error'][] = "Users table does not exist in the database.";
}

echo '<div class="fix-status">';
if (!empty($messages['success'])) {
    foreach ($messages['success'] as $success_message) {
        echo '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' . $success_message . '</div>';
    }
}
if (!empty($messages['error'])) {
    foreach ($messages['error'] as $error_message) {
        echo '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> ' . $error_message . '</div>';
    }
}
if (!empty($messages['info'])) {
    foreach ($messages['info'] as $info_message) {
        echo '<div class="alert alert-info"><i class="fas fa-info-circle"></i> ' . $info_message . '</div>';
    }
}
echo '</div></div>';

// Reset messages for next check
$messages = [
    'success' => [],
    'error' => [],
    'info' => []
];

// 2. Check 'rating' column in 'testimonials' table
echo '<div class="fix-item">
        <h5><i class="fas fa-database"></i> Checking \'rating\' column in \'testimonials\' table</h5>';

$testimonials_table_exists = $conn->query("SHOW TABLES LIKE 'testimonials'")->num_rows > 0;
if ($testimonials_table_exists) {
    check_and_add_column($conn, 'testimonials', 'rating', 'INT NOT NULL DEFAULT 5');
    
    // Also check for 'course_name' column which might be needed
    check_and_add_column($conn, 'testimonials', 'course_name', 'VARCHAR(255) DEFAULT NULL');
} else {
    // If testimonials table doesn't exist, create it
    $create_testimonials = $conn->query("CREATE TABLE IF NOT EXISTS testimonials (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        content TEXT NOT NULL,
        rating INT NOT NULL DEFAULT 5,
        course_name VARCHAR(255) DEFAULT NULL,
        status ENUM('pending', 'approved', 'rejected') NOT NULL DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    )");
    
    if ($create_testimonials) {
        $messages['success'][] = "Created testimonials table with all required columns.";
    } else {
        $messages['error'][] = "Failed to create testimonials table: " . $conn->error;
    }
}

echo '<div class="fix-status">';
if (!empty($messages['success'])) {
    foreach ($messages['success'] as $success_message) {
        echo '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' . $success_message . '</div>';
    }
}
if (!empty($messages['error'])) {
    foreach ($messages['error'] as $error_message) {
        echo '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> ' . $error_message . '</div>';
    }
}
if (!empty($messages['info'])) {
    foreach ($messages['info'] as $info_message) {
        echo '<div class="alert alert-info"><i class="fas fa-info-circle"></i> ' . $info_message . '</div>';
    }
}
echo '</div></div>';

// 3. Configure user avatar for navigation
echo '<div class="fix-item">
        <h5><i class="fas fa-user-circle"></i> Configuring user avatar integration</h5>';

// Check for profile_image column in users table
$profile_image_exists = false;
if ($users_table_exists) {
    $profile_image_exists = $conn->query("SHOW COLUMNS FROM users LIKE 'profile_image'")->num_rows > 0;
    
    if (!$profile_image_exists) {
        check_and_add_column($conn, 'users', 'profile_image', 'VARCHAR(255) DEFAULT NULL');
    } else {
        echo '<div class="alert alert-info"><i class="fas fa-info-circle"></i> Profile image column already exists in users table.</div>';
    }
    
    // Verify avatar display in both admin and frontend navbars
    echo '<div class="alert alert-info">
            <i class="fas fa-info-circle"></i> User avatars should be automatically displayed in the navigation if the profile_image column exists and contains valid image paths.
          </div>';
    
    // Check if the avatar rendering code exists in the header files
    $admin_header_avatar = false;
    $frontend_header_avatar = false;
    
    if (file_exists('../includes/header.php')) {
        $admin_header_contents = file_get_contents('../includes/header.php');
        if (strpos($admin_header_contents, 'profile_image') !== false && 
            strpos($admin_header_contents, 'user-image') !== false) {
            $admin_header_avatar = true;
            echo '<div class="alert alert-success"><i class="fas fa-check-circle"></i> Admin panel avatar display code is properly configured.</div>';
        } else {
            echo '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> Admin panel avatar display might need configuration in admin/includes/header.php.</div>';
        }
    } else {
        echo '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> Could not locate admin header file to check avatar configuration.</div>';
    }
    
    if (file_exists('../../includes/header.php')) {
        $frontend_header_contents = file_get_contents('../../includes/header.php');
        if (strpos($frontend_header_contents, 'avatar-toggle') !== false && 
            strpos($frontend_header_contents, 'avatar-img') !== false) {
            $frontend_header_avatar = true;
            echo '<div class="alert alert-success"><i class="fas fa-check-circle"></i> Frontend avatar display code is properly configured.</div>';
        } else {
            echo '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> Frontend avatar display might need configuration in includes/header.php.</div>';
        }
    } else {
        echo '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> Could not locate frontend header file to check avatar configuration.</div>';
    }
    
    // Show test avatar upload option
    echo '<div class="card mt-3">
            <div class="card-header">
                <h6><i class="fas fa-image"></i> Test Avatar Upload</h6>
            </div>
            <div class="card-body">
                <p>If you want to test the avatar functionality, you can upload a profile image for your account:</p>
                <form action="upload_avatar.php" method="post" enctype="multipart/form-data" class="mt-2">
                    <div class="mb-3">
                        <label for="avatar" class="form-label">Select Avatar Image:</label>
                        <input type="file" class="form-control" id="avatar" name="avatar" accept="image/*">
                    </div>
                    <button type="submit" class="btn btn-primary">Upload Avatar</button>
                </form>
                <div class="mt-3">
                    <small class="text-muted">
                        <i class="fas fa-info-circle"></i> Note: We\'ll automatically create the upload_avatar.php script if it doesn\'t exist.
                    </small>
                </div>
            </div>
        </div>';
    
    // Check if the upload_avatar.php script exists or create it
    if (!file_exists('upload_avatar.php')) {
        $upload_script = '<?php
// Start session if not already started
if (session_status() === PHP_SESSION_INACTIVE) {
    session_start();
}

// Check if user is logged in and is admin
if (!isset($_SESSION[\'user_id\']) || $_SESSION[\'role\'] !== \'admin\') {
    $_SESSION[\'error_message\'] = "Access denied. You must be logged in as an administrator.";
    header(\'Location: ../login.php\');
    exit;
}

// Include database configuration
require_once \'db_config.php\';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if file was uploaded without errors
    if (isset($_FILES["avatar"]) && $_FILES["avatar"]["error"] == 0) {
        $allowed = ["jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"];
        $filename = $_FILES["avatar"]["name"];
        $filetype = $_FILES["avatar"]["type"];
        $filesize = $_FILES["avatar"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (!array_key_exists($ext, $allowed)) {
            $_SESSION[\'error_message\'] = "Error: Please select a valid file format.";
            header("Location: fix_missing_columns.php");
            exit;
        }
    
        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if ($filesize > $maxsize) {
            $_SESSION[\'error_message\'] = "Error: File size is larger than the allowed limit.";
            header("Location: fix_missing_columns.php");
            exit;
        }
    
        // Verify MIME type of the file
        if (in_array($filetype, $allowed)) {
            // Create uploads directory if it doesn\'t exist
            $upload_dir = "../../uploads/avatars/";
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Create unique filename
            $new_filename = uniqid() . "." . $ext;
            $upload_path = $upload_dir . $new_filename;
            
            // Save the file
            if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $upload_path)) {
                // Update the user\'s profile_image in the database
                $relative_path = "uploads/avatars/" . $new_filename;
                $user_id = $_SESSION[\'user_id\'];
                
                $stmt = $conn->prepare("UPDATE users SET profile_image = ? WHERE id = ?");
                $stmt->bind_param("si", $relative_path, $user_id);
                
                if ($stmt->execute()) {
                    $_SESSION[\'success_message\'] = "Avatar uploaded successfully!";
                } else {
                    $_SESSION[\'error_message\'] = "Error updating database: " . $conn->error;
                }
                $stmt->close();
            } else {
                $_SESSION[\'error_message\'] = "Error: There was a problem uploading your file. Please try again.";
            }
        } else {
            $_SESSION[\'error_message\'] = "Error: There was a problem with the file type. Please try again.";
        }
    } else {
        $_SESSION[\'error_message\'] = "Error: " . $_FILES["avatar"]["error"];
    }
    
    header("Location: fix_missing_columns.php");
    exit;
}

// If not a POST request, redirect to the fix page
header("Location: fix_missing_columns.php");
exit;
?>';
        
        // Create the upload script
        file_put_contents('upload_avatar.php', $upload_script);
        echo '<div class="alert alert-success"><i class="fas fa-check-circle"></i> Created avatar upload handler script.</div>';
    }
} else {
    echo '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Cannot configure user avatars: users table does not exist.</div>';
}

echo '</div></div>';

// Check instructor-details.php file
echo '<div class="fix-item">
        <h5><i class="fas fa-file-code"></i> Checking instructor-details.php file</h5>';

if (file_exists('../../instructor-details.php')) {
    echo '<div class="alert alert-info"><i class="fas fa-info-circle"></i> instructor-details.php file exists and has been updated to check for the designation column.</div>';
} else {
    echo '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> instructor-details.php file could not be located. If you have instructor profiles on your site, make sure the file exists and handles the designation column properly.</div>';
}

// Reset messages for next check
$messages = [
    'success' => [],
    'error' => [],
    'info' => []
];

// 4. Check for course_code in courses table
echo '<div class="fix-item">
        <h5><i class="fas fa-database"></i> Checking \'course_code\' column in \'courses\' table</h5>';

$courses_table_exists = $conn->query("SHOW TABLES LIKE 'courses'")->num_rows > 0;
if ($courses_table_exists) {
    $result = check_and_add_column($conn, 'courses', 'course_code', 'VARCHAR(20) DEFAULT NULL');
    
    // If the column was just added, update existing courses with default codes
    if ($result && empty($messages['info'])) {
        // Get all courses that don't have a course code
        $update_query = $conn->query("SELECT id FROM courses WHERE course_code IS NULL");
        if ($update_query && $update_query->num_rows > 0) {
            $updated_count = 0;
            while ($course = $update_query->fetch_assoc()) {
                $course_id = $course['id'];
                $default_code = 'C' . sprintf('%03d', $course_id);
                
                // Update the course with a default code
                if ($conn->query("UPDATE courses SET course_code = '$default_code' WHERE id = $course_id")) {
                    $updated_count++;
                }
            }
            
            if ($updated_count > 0) {
                $messages['success'][] = "Updated $updated_count courses with default course codes.";
            }
        }
    }
} else {
    $messages['error'][] = "Courses table does not exist in the database.";
}

echo '<div class="fix-status">';
if (!empty($messages['success'])) {
    foreach ($messages['success'] as $success_message) {
        echo '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' . $success_message . '</div>';
    }
}
if (!empty($messages['error'])) {
    foreach ($messages['error'] as $error_message) {
        echo '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> ' . $error_message . '</div>';
    }
}
if (!empty($messages['info'])) {
    foreach ($messages['info'] as $info_message) {
        echo '<div class="alert alert-info"><i class="fas fa-info-circle"></i> ' . $info_message . '</div>';
    }
}
echo '</div></div>';

// Reset messages for next check
$messages = [
    'success' => [],
    'error' => [],
    'info' => []
];

// Navigation links
echo '<div class="navigation">
        <a href="../dashboard.php" class="btn btn-primary"><i class="fas fa-home"></i> Return to Dashboard</a>
        <a href="../users.php" class="btn btn-success"><i class="fas fa-users"></i> Manage Users</a>
        <a href="../testimonials.php" class="btn btn-info"><i class="fas fa-quote-left"></i> Manage Testimonials</a>
      </div>';

echo '</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>';

// Close database connection
$conn->close();
?>