<?php
// Start session and check if user is logged in
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

// Include config file
require_once 'includes/config.php';

// Set headers for HTML output
header('Content-Type: text/html; charset=utf-8');
echo "<pre>";

try {
    // Check if property_images table exists
    $table_check = $conn->query("SHOW TABLES LIKE 'property_images'");
    if ($table_check->num_rows === 0) {
        die("property_images table does not exist. No migration needed.");
    }

    // Get all property images that aren't already in gallery_images
    $sql = "SELECT pi.*, pt.name as property_type_name 
            FROM property_images pi
            JOIN property_types pt ON pi.property_type_id = pt.id
            LEFT JOIN gallery_images gi ON pi.image_path = gi.image_path
            WHERE gi.id IS NULL";
    
    $result = $conn->query($sql);
    $images_to_migrate = $result->fetch_all(MYSQLI_ASSOC);
    $count = count($images_to_migrate);
    
    if ($count === 0) {
        echo "No images to migrate. All property images already exist in gallery_images.\n";
        exit;
    }
    
    echo "Found $count images to migrate.\n\n";
    
    // Prepare insert statement for gallery_images
    $insert_sql = "INSERT INTO gallery_images 
                  (category_id, title, description, image_path, thumbnail_path, is_featured, uploaded_at, updated_at)
                  VALUES (?, ?, ?, ?, ?, 0, NOW(), NOW())";
    $stmt = $conn->prepare($insert_sql);
    
    // Get or create a gallery category for property images
    $category_sql = "SELECT id FROM gallery_categories WHERE type = 'property' LIMIT 1";
    $category_result = $conn->query($category_sql);
    
    if ($category_result->num_rows === 0) {
        // Create a default property category if it doesn't exist
        $conn->query("INSERT INTO gallery_categories (name, description, type) 
                     VALUES ('Property Gallery', 'Property images gallery', 'property')");
        $category_id = $conn->insert_id;
        echo "Created new property gallery category with ID: $category_id\n";
    } else {
        $category_id = $category_result->fetch_assoc()['id'];
        echo "Using existing property gallery category ID: $category_id\n";
    }
    
    // Process each image
    $migrated = 0;
    $errors = [];
    
    foreach ($images_to_migrate as $image) {
        $title = 'Property: ' . $image['property_type_name'];
        $description = 'Property type image: ' . $image['property_type_name'];
        
        $stmt->bind_param("issss", 
            $category_id,
            $title,
            $description,
            $image['image_path'],
            $image['image_path'] // Using same path for thumbnail for now
        );
        
        if ($stmt->execute()) {
            $migrated++;
            echo "Migrated: {$image['image_path']}\n";
        } else {
            $errors[] = "Failed to migrate {$image['image_path']}: " . $conn->error;
        }
    }
    
    echo "\nMigration complete. Successfully migrated $migrated of $count images.\n";
    
    if (!empty($errors)) {
        echo "\nErrors encountered:\n";
        foreach ($errors as $error) {
            echo "- $error\n";
        }
    }
    
    // Optional: Drop the property_images table if all migrations were successful
    if ($migrated === $count && $count > 0) {
        echo "\nAll images migrated successfully. Would you like to drop the property_images table? ";
        echo "<form method='post'><input type='submit' name='drop_table' value='Yes, drop the table'>";
        echo "<input type='hidden' name='confirm' value='1'></form>";
        
        if (isset($_POST['confirm']) && $_POST['confirm'] == 1) {
            $conn->query("DROP TABLE IF EXISTS property_images");
            echo "\n\nproperty_images table has been dropped.";
        }
    }
    
} catch (Exception $e) {
    echo "Error during migration: " . $e->getMessage();
}

echo "</pre>";
?>
