<?php
session_start();
error_reporting(0);
include('includes/dbconnection.php');

echo "<h2>Fixing Brand Management System</h2>";

// Step 1: Add BrandIcon column if it doesn't exist
$check_column = mysqli_query($con, "SHOW COLUMNS FROM tblbrand LIKE 'BrandIcon'");

if (mysqli_num_rows($check_column) == 0) {
    $add_column = mysqli_query($con, "ALTER TABLE `tblbrand` ADD `BrandIcon` VARCHAR(255) NULL AFTER `BrandName`");
    
    if ($add_column) {
        echo "<p style='color: green;'>✅ BrandIcon column added successfully!</p>";
        
        // Update existing brands with default icons
        $update_icons = mysqli_query($con, "UPDATE `tblbrand` SET `BrandIcon` = '📱' WHERE `BrandIcon` IS NULL OR `BrandIcon` = ''");
        
        if ($update_icons) {
            echo "<p style='color: green;'>✅ Default icons assigned to existing brands!</p>";
        }
    } else {
        echo "<p style='color: red;'>❌ Error adding column: " . mysqli_error($con) . "</p>";
    }
} else {
    echo "<p style='color: blue;'>ℹ️ BrandIcon column already exists!</p>";
}

// Step 2: Create upload directory
$upload_dir = 'images/brand_icons/';
if (!file_exists($upload_dir)) {
    if (mkdir($upload_dir, 0777, true)) {
        echo "<p style='color: green;'>✅ Upload directory created: $upload_dir</p>";
    } else {
        echo "<p style='color: red;'>❌ Failed to create upload directory: $upload_dir</p>";
    }
} else {
    echo "<p style='color: blue;'>ℹ️ Upload directory already exists: $upload_dir</p>";
}

// Step 3: Test database connection and table structure
$test_query = mysqli_query($con, "SELECT * FROM tblbrand LIMIT 1");
if ($test_query) {
    echo "<p style='color: green;'>✅ Database connection working!</p>";
    
    // Show table structure
    $structure_query = mysqli_query($con, "DESCRIBE tblbrand");
    echo "<h3>Current Table Structure:</h3>";
    echo "<table border='1' style='border-collapse: collapse; margin: 10px 0;'>";
    echo "<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th><th>Extra</th></tr>";
    
    while ($row = mysqli_fetch_array($structure_query)) {
        echo "<tr>";
        echo "<td>" . $row['Field'] . "</td>";
        echo "<td>" . $row['Type'] . "</td>";
        echo "<td>" . $row['Null'] . "</td>";
        echo "<td>" . $row['Key'] . "</td>";
        echo "<td>" . $row['Default'] . "</td>";
        echo "<td>" . $row['Extra'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<p style='color: red;'>❌ Database connection failed: " . mysqli_error($con) . "</p>";
}

echo "<p><a href='manage-brand.php' style='background: #007cba; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Go to Manage Brands</a></p>";
?>
