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

<?php
// Include header
require_once 'includes/header.php';

// Check if user has admin privileges
if ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director') {
    header('Location: ../login.php');
    exit;
}

// Process maintenance actions
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['verify_tables'])) {
        // Include verify tables script but capture output
        ob_start();
        include 'database/verify_tables.php';
        $output = ob_get_clean();
        
        $success_message = "Database tables verification completed. Please check the results below.";
    }
    
    if (isset($_POST['repair_settings'])) {
        // Drop and recreate settings table
        $conn->query("DROP TABLE IF EXISTS settings");
        
        $sql_settings = "CREATE TABLE settings (
            id INT(11) NOT NULL AUTO_INCREMENT,
            setting_key VARCHAR(100) NOT NULL,
            setting_value TEXT,
            setting_description TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY (setting_key)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        if ($conn->query($sql_settings)) {
            // Insert default settings
            $default_settings = [
                ['school_name', 'Popular Computer Institute', 'School Name'],
                ['school_address', 'Your Institute Address, City, State, PIN', 'School Address'],
                ['school_phone', '+91 9876 543 210', 'School Phone Number'],
                ['school_email', '[email protected]', 'School Email Address'],
                ['school_logo', 'assets/img/logo.png', 'School Logo Path - This should be relative to the site root'],
                ['school_website', 'https://www.popularcomputerinstitute.com', 'School Website URL']
            ];
            
            $success = true;
            foreach ($default_settings as $setting) {
                $insert_query = "INSERT INTO settings (setting_key, setting_value, setting_description) VALUES (?, ?, ?)";
                $stmt = $conn->prepare($insert_query);
                $stmt->bind_param("sss", $setting[0], $setting[1], $setting[2]);
                if (!$stmt->execute()) {
                    $success = false;
                    $error_message = "Failed to insert setting: " . $setting[0] . " - " . $conn->error;
                    break;
                }
            }
            
            if ($success) {
                $success_message = "Settings table has been repaired successfully.";
            }
        } else {
            $error_message = "Failed to recreate settings table: " . $conn->error;
        }
    }
    
    if (isset($_POST['optimize_tables'])) {
        // Get all tables
        $tables_result = $conn->query("SHOW TABLES");
        $tables = [];
        while ($row = $tables_result->fetch_row()) {
            $tables[] = $row[0];
        }
        
        // Optimize each table
        $success = true;
        foreach ($tables as $table) {
            if (!$conn->query("OPTIMIZE TABLE `$table`")) {
                $success = false;
                $error_message = "Failed to optimize table: $table - " . $conn->error;
                break;
            }
        }
        
        if ($success) {
            $success_message = "All database tables have been optimized successfully.";
        }
    }

    if (isset($_POST['fix_logo_path'])) {
        // Fix the logo path in settings table
        $logo_path = 'assets/img/logo.png';
        $update_query = "UPDATE settings SET setting_value = ? WHERE setting_key = 'school_logo'";
        $stmt = $conn->prepare($update_query);
        
        if ($stmt) {
            $stmt->bind_param("s", $logo_path);
            if ($stmt->execute()) {
                $success_message = "Logo path has been reset to the default path: " . $logo_path;
            } else {
                $error_message = "Failed to update logo path: " . $conn->error;
            }
        } else {
            $error_message = "Failed to prepare statement: " . $conn->error;
        }
    }
}

// Get database information
$db_info = [];
$db_info['server_version'] = $conn->server_info;
$db_info['database_name'] = DB_NAME;

// Get table count
$tables_result = $conn->query("SHOW TABLES");
$db_info['table_count'] = $tables_result->num_rows;

// Get total database size
$size_result = $conn->query("SELECT SUM(data_length + index_length) AS size FROM information_schema.TABLES WHERE table_schema = '" . DB_NAME . "'");
$size_row = $size_result->fetch_assoc();
$db_info['total_size'] = $size_row['size'] ? round($size_row['size'] / (1024 * 1024), 2) : 0;

// Get enrollment applications count
$app_result = $conn->query("SELECT COUNT(*) AS count FROM enrollment_applications");
$app_row = $app_result->fetch_assoc();
$db_info['applications_count'] = $app_row['count'] ?? 0;

// Get enrollments count
$enroll_result = $conn->query("SELECT COUNT(*) AS count FROM enrollments");
$enroll_row = $enroll_result->fetch_assoc();
$db_info['enrollments_count'] = $enroll_row['count'] ?? 0;
?>

<!-- Begin Page Content -->
<div class="container-fluid">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Database Maintenance</h1>
    </div>
    
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo $success_message; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?php echo $error_message; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-lg-6 mb-4">
            <!-- Database Information Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Database Information</h6>
                </div>
                <div class="card-body">
                    <div class="mb-4">
                        <div class="row mb-2">
                            <div class="col-md-5 font-weight-bold">Database Server:</div>
                            <div class="col-md-7"><?php echo htmlspecialchars($db_info['server_version']); ?></div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-5 font-weight-bold">Database Name:</div>
                            <div class="col-md-7"><?php echo htmlspecialchars($db_info['database_name']); ?></div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-5 font-weight-bold">Number of Tables:</div>
                            <div class="col-md-7"><?php echo $db_info['table_count']; ?></div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-5 font-weight-bold">Total Database Size:</div>
                            <div class="col-md-7"><?php echo $db_info['total_size']; ?> MB</div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-5 font-weight-bold">Applications Count:</div>
                            <div class="col-md-7"><?php echo $db_info['applications_count']; ?></div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-5 font-weight-bold">Enrollments Count:</div>
                            <div class="col-md-7"><?php echo $db_info['enrollments_count']; ?></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Maintenance Actions Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Maintenance Actions</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-2">
                            <form method="post" action="">
                                <button type="submit" name="verify_tables" class="btn btn-primary btn-block">
                                    <i class="fas fa-check-circle mr-1"></i> Verify Tables
                                </button>
                            </form>
                        </div>
                        <div class="col-md-4 mb-2">
                            <form method="post" action="" onsubmit="return confirm('Are you sure you want to repair the settings table? This will remove all existing settings and restore defaults.');">
                                <button type="submit" name="repair_settings" class="btn btn-warning btn-block">
                                    <i class="fas fa-tools mr-1"></i> Repair Settings
                                </button>
                            </form>
                        </div>
                        <div class="col-md-4 mb-2">
                            <form method="post" action="" onsubmit="return confirm('Are you sure you want to optimize all database tables?');">
                                <button type="submit" name="optimize_tables" class="btn btn-success btn-block">
                                    <i class="fas fa-bolt mr-1"></i> Optimize Tables
                                </button>
                            </form>
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-md-4 mb-2">
                            <form method="post" action="" onsubmit="return confirm('Are you sure you want to reset the logo path to default?');">
                                <button type="submit" name="fix_logo_path" class="btn btn-info btn-block">
                                    <i class="fas fa-image mr-1"></i> Fix Logo Path
                                </button>
                            </form>
                        </div>
                    </div>
                    <div class="alert alert-info mt-3">
                        <i class="fas fa-info-circle mr-1"></i> 
                        Use these tools carefully. "Verify Tables" will check and create missing tables.
                        "Repair Settings" will recreate the settings table with default values.
                        "Optimize Tables" will optimize database tables for better performance.
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6 mb-4">
            <!-- Verification Results Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Verification Results</h6>
                </div>
                <div class="card-body">
                    <?php if (isset($output)): ?>
                        <div class="verification-output" style="height: 400px; overflow-y: auto;">
                            <?php echo $output; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="fas fa-database fa-3x mb-3 text-gray-300"></i>
                            <p class="mb-0 text-gray-500">Click "Verify Tables" to check database structure</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Troubleshooting Tips Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Troubleshooting Tips</h6>
                </div>
                <div class="card-body">
                    <h5 class="text-primary"><i class="fas fa-question-circle mr-1"></i> Common Issues</h5>
                    <ul class="list-group list-group-flush mb-4">
                        <li class="list-group-item">
                            <strong>Missing Tables</strong>: Use "Verify Tables" to create missing tables
                        </li>
                        <li class="list-group-item">
                            <strong>Settings Table Issues</strong>: Use "Repair Settings" to recreate the settings table
                        </li>
                        <li class="list-group-item">
                            <strong>Slow Database</strong>: Use "Optimize Tables" to improve performance
                        </li>
                    </ul>
                    
                    <h5 class="text-primary"><i class="fas fa-lightbulb mr-1"></i> Quick Tips</h5>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">
                            Run "Verify Tables" after upgrading the software to ensure database compatibility
                        </li>
                        <li class="list-group-item">
                            Regularly optimize tables if you have many enrollments for better performance
                        </li>
                        <li class="list-group-item">
                            Backup your database before performing major maintenance operations
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Include footer
include_once 'includes/footer.php';
?>