<?php
/**
 * Fix for hostel system
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config/database.php';

echo "<h2>Hostel System Fix Tool</h2>";

try {
    // Drop and recreate hostel_fees table with correct structure based on hostel_fees.php
    try {
        $pdo->exec("DROP TABLE IF EXISTS hostel_fees");
        echo "<p style='color: orange;'>🗑️ Dropped existing hostel_fees table</p>";
    } catch (Exception $e) {
        echo "<p style='color: orange;'>⚠️ Could not drop hostel_fees table: " . $e->getMessage() . "</p>";
    }
    
    // Create hostel_fees table with structure that matches hostel_fees.php expectations
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS hostel_fees (
            id INT AUTO_INCREMENT PRIMARY KEY,
            allocation_id INT NOT NULL,
            fee_type VARCHAR(50) NOT NULL,
            amount DECIMAL(10,2) NOT NULL,
            due_date DATE,
            academic_year VARCHAR(10),
            month VARCHAR(20),
            description TEXT,
            paid_amount DECIMAL(10,2) DEFAULT 0.00,
            status ENUM('pending', 'partial', 'paid', 'overdue') DEFAULT 'pending',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (allocation_id) REFERENCES hostel_allocations(id) ON DELETE CASCADE
        )
    ");
    echo "<p style='color: green;'>✅ hostel_fees table created with correct structure</p>";

    // Create hostel_fee_payments table which is referenced in hostel_fees.php
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS hostel_fee_payments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            fee_id INT NOT NULL,
            amount DECIMAL(10,2) NOT NULL,
            payment_method ENUM('cash', 'bank', 'online', 'cheque') DEFAULT 'cash',
            transaction_id VARCHAR(100),
            payment_date DATE NOT NULL,
            received_by INT,
            remarks TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (fee_id) REFERENCES hostel_fees(id) ON DELETE CASCADE,
            FOREIGN KEY (received_by) REFERENCES users(id) ON DELETE SET NULL
        )
    ");
    echo "<p style='color: green;'>✅ hostel_fee_payments table created</p>";

    // Create other hostel tables if they don't exist
    $hostel_tables_sql = [
        'hostel_buildings' => "CREATE TABLE IF NOT EXISTS hostel_buildings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            building_name VARCHAR(100) NOT NULL,
            building_code VARCHAR(20) UNIQUE NOT NULL,
            address TEXT,
            total_floors INT DEFAULT 1,
            warden_name VARCHAR(100),
            warden_phone VARCHAR(20),
            warden_email VARCHAR(100),
            status ENUM('active', 'inactive', 'maintenance') DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )",
        
        'hostel_rooms' => "CREATE TABLE IF NOT EXISTS hostel_rooms (
            id INT AUTO_INCREMENT PRIMARY KEY,
            building_id INT NOT NULL,
            room_number VARCHAR(20) NOT NULL,
            floor_number INT DEFAULT 1,
            room_type ENUM('single', 'double', 'triple', 'dormitory') DEFAULT 'double',
            capacity INT DEFAULT 2,
            current_occupancy INT DEFAULT 0,
            amenities TEXT,
            monthly_rent DECIMAL(10,2) DEFAULT 0.00,
            status ENUM('available', 'occupied', 'maintenance', 'reserved') DEFAULT 'available',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (building_id) REFERENCES hostel_buildings(id) ON DELETE CASCADE,
            UNIQUE KEY unique_building_room (building_id, room_number)
        )",
        
        'hostel_allocations' => "CREATE TABLE IF NOT EXISTS hostel_allocations (
            id INT AUTO_INCREMENT PRIMARY KEY,
            student_id INT NOT NULL,
            room_id INT NOT NULL,
            allocation_date DATE NOT NULL,
            valid_until DATE,
            monthly_rent DECIMAL(10,2) DEFAULT 0.00,
            security_deposit DECIMAL(10,2) DEFAULT 0.00,
            status ENUM('active', 'vacated', 'suspended') DEFAULT 'active',
            vacated_date DATE,
            remarks TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
            FOREIGN KEY (room_id) REFERENCES hostel_rooms(id) ON DELETE CASCADE,
            UNIQUE KEY unique_student_allocation (student_id, status)
        )"
    ];

    echo "<h3>Creating Other Hostel Tables...</h3>";
    $created_tables = [];
    
    foreach ($hostel_tables_sql as $table_name => $sql) {
        try {
            $pdo->exec($sql);
            echo "<p style='color: green;'>✅ $table_name table - OK</p>";
            $created_tables[] = $table_name;
        } catch (Exception $e) {
            echo "<p style='color: red;'>❌ Error creating $table_name table: " . $e->getMessage() . "</p>";
        }
    }

    // Check login status
    session_start();
    if (isset($_SESSION['user_id'])) {
        echo "<p style='color: green;'>✅ You are currently logged in as: {$_SESSION['username']} (Role: {$_SESSION['user_role']})</p>";
    } else {
        echo "<p style='color: orange;'>⚠️ You are NOT logged in. Please log in first.</p>";
    }

    echo "<h3>Hostel Management Pages:</h3>";
    echo "<ul>";
    echo "<li><a href='admin/hostel/buildings.php'>🏢 Hostel Buildings</a></li>";
    echo "<li><a href='admin/hostel/rooms.php'>🚪 Hostel Rooms</a></li>";
    echo "<li><a href='admin/hostel/allocations.php'>👥 Room Allocations</a></li>";
    echo "<li><a href='admin/hostel/hostel_fees.php'>💰 Hostel Fees</a></li>";
    echo "<li><a href='admin/hostel/index.php'>🏨 Hostel Dashboard</a></li>";
    echo "</ul>";

} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Error: " . $e->getMessage() . "</p>";
}

echo "<h3>Quick Actions:</h3>";
echo "<ul>";
echo "<li><a href='force_login.php'>🔐 Force Login as Admin</a></li>";
echo "<li><a href='login.php'>🔐 Normal Login Page</a> (Default: admin/admin123)</li>";
echo "<li><a href='index.php'>🏠 Home Page</a></li>";
echo "<li><a href='fix_transport_system.php'>🚌 Fix Transport System</a></li>";
echo "</ul>";

echo "<p><strong>Note:</strong> If hostel pages still don't load after fixing tables, make sure you're logged in first.</p>";
?>