<!DOCTYPE html>
<html>
<head>
    <title>Fix Voucher Schema</title>
</head>
<body>
    <h1>Fix Voucher Schema</h1>
    <p>Click the button below to fix the voucher_codes table schema to allow NULL values for bulk voucher generation.</p>
    
    <form method="POST">
        <button type="submit" name="fix_schema">Fix Schema Now</button>
    </form>
    
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['fix_schema'])) {
        include 'includes/db.php';
        
        echo "<h2>Fixing voucher_codes table schema...</h2>";
        
        // Check current table structure
        echo "<h3>Current table structure:</h3>";
        $result = $conn->query("DESCRIBE voucher_codes");
        echo "<table border='1'><tr><th>Field</th><th>Type</th><th>Null</th></tr>";
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row['Field'] . "</td><td>" . $row['Type'] . "</td><td>" . $row['Null'] . "</td></tr>";
        }
        echo "</table>";
        
        // Drop foreign key constraints if they exist
        echo "<h3>Dropping foreign key constraints...</h3>";
        $conn->query("ALTER TABLE voucher_codes DROP FOREIGN KEY IF EXISTS voucher_codes_ibfk_1");
        $conn->query("ALTER TABLE voucher_codes DROP FOREIGN KEY IF EXISTS voucher_codes_ibfk_2");
        echo "Foreign key constraints dropped.<br>";
        
        // Allow NULL values for student_id and program_id
        echo "<h3>Allowing NULL values for student_id and program_id...</h3>";
        $conn->query("ALTER TABLE voucher_codes MODIFY student_id INT NULL");
        $conn->query("ALTER TABLE voucher_codes MODIFY program_id INT NULL");
        echo "NULL values allowed.<br>";
        
        // Re-add foreign key constraints with ON DELETE SET NULL
        echo "<h3>Re-adding foreign key constraints...</h3>";
        $conn->query("ALTER TABLE voucher_codes ADD CONSTRAINT voucher_codes_ibfk_1 
                      FOREIGN KEY (student_id) REFERENCES users(id) ON DELETE SET NULL");
        $conn->query("ALTER TABLE voucher_codes ADD CONSTRAINT voucher_codes_ibfk_2 
                      FOREIGN KEY (program_id) REFERENCES programs(id) ON DELETE SET NULL");
        echo "Foreign key constraints re-added with ON DELETE SET NULL.<br>";
        
        // Verify changes
        echo "<h3>Updated table structure:</h3>";
        $result = $conn->query("DESCRIBE voucher_codes");
        echo "<table border='1'><tr><th>Field</th><th>Type</th><th>Null</th></tr>";
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row['Field'] . "</td><td>" . $row['Type'] . "</td><td>" . $row['Null'] . "</td></tr>";
        }
        echo "</table>";
        
        echo "<h2>Schema fixed successfully! Bulk voucher generation should now work.</h2>";
        echo "<p><a href='admin/voucher_management.php'>Go to Voucher Management</a></p>";
    }
    ?>
</body>
</html>
