<?php
/**
 * Initialize Cart Table
 * Creates the cart table if it doesn't exist
 */

require_once 'config.php';

try {
    // Check if cart table exists
    $result = $conn->query("SHOW TABLES LIKE 'cart'");
    
    if ($result->num_rows == 0) {
        // Create cart table
        $sql = "
            CREATE TABLE cart (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                item_id INT NOT NULL,
                quantity INT DEFAULT 1,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
                FOREIGN KEY (item_id) REFERENCES menu_items(id) ON DELETE CASCADE,
                UNIQUE KEY unique_user_item (user_id, item_id),
                INDEX idx_user_id (user_id),
                INDEX idx_item_id (item_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ";
        
        if ($conn->query($sql)) {
            echo json_encode(['success' => true, 'message' => 'Cart table created successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error creating cart table: ' . $conn->error]);
        }
    } else {
        echo json_encode(['success' => true, 'message' => 'Cart table already exists']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
