<?php
require_once 'config/database.php';

echo "Creating orders tables...\n";

try {
    // Create orders table
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS orders (
            id TEXT PRIMARY KEY,
            user_id TEXT,
            order_number TEXT UNIQUE NOT NULL,
            status TEXT DEFAULT 'pending',
            payment_status TEXT DEFAULT 'unpaid',
            total_amount REAL DEFAULT 0.00,
            currency TEXT DEFAULT 'USD',
            payment_method TEXT,
            customer_email TEXT,
            customer_name TEXT,
            billing_address TEXT,
            notes TEXT,
            created_at DATETIME DEFAULT (datetime('now')),
            updated_at DATETIME DEFAULT (datetime('now')),
            FOREIGN KEY (user_id) REFERENCES users(id)
        )
    ");
    echo "✓ Created 'orders' table\n";

    // Create order_items table
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS order_items (
            id TEXT PRIMARY KEY,
            order_id TEXT NOT NULL,
            product_type TEXT NOT NULL,
            product_name TEXT NOT NULL,
            quantity INTEGER DEFAULT 1,
            unit_price REAL DEFAULT 0.00,
            total_price REAL DEFAULT 0.00,
            metadata TEXT,
            created_at DATETIME DEFAULT (datetime('now')),
            FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
        )
    ");
    echo "✓ Created 'order_items' table\n";

    // Create indexes for better query performance
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_orders_created_at ON orders(created_at)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_order_items_order_id ON order_items(order_id)");
    
    echo "✓ Created indexes\n";

    echo "\n✅ Orders tables created successfully!\n";
} catch (PDOException $e) {
    echo "❌ Error creating tables: " . $e->getMessage() . "\n";
    exit(1);
}
?>
