<?php
// Create API keys table for portal integration
include 'includes/db.php';

echo "Creating API keys table for portal integration...\n";

// Create api_keys table
$sql = "CREATE TABLE IF NOT EXISTS api_keys (
    id INT AUTO_INCREMENT PRIMARY KEY,
    portal_name VARCHAR(100) NOT NULL,
    description TEXT,
    api_key VARCHAR(100) UNIQUE NOT NULL,
    generated_by INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_used TIMESTAMP NULL,
    status ENUM('active', 'inactive') DEFAULT 'active',
    FOREIGN KEY (generated_by) REFERENCES users(id) ON DELETE CASCADE
)";

if ($conn->query($sql) === TRUE) {
    echo "API keys table created successfully.\n";
} else {
    echo "Error creating API keys table: " . $conn->error . "\n";
}

// Create api_logs table for tracking API usage
$sql = "CREATE TABLE IF NOT EXISTS api_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    api_key_id INT NOT NULL,
    endpoint VARCHAR(255) NOT NULL,
    method VARCHAR(10) NOT NULL,
    request_data TEXT,
    response_code INT,
    ip_address VARCHAR(45),
    user_agent TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE CASCADE
)";

if ($conn->query($sql) === TRUE) {
    echo "API logs table created successfully.\n";
} else {
    echo "Error creating API logs table: " . $conn->error . "\n";
}

echo "Portal integration database setup completed.\n";
$conn->close();
?>
