<?php
// API Key Management class
class ApiKeyManager {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    public function generateApiKey() {
        return 'ak_' . bin2hex(random_bytes(24));
    }

    public function createApiKey($data) {
        try {
            $apiKey = $this->generateApiKey();

            $query = "INSERT INTO api_keys (api_key, name, email, company, purpose, usage_limit, expires_at)
                      VALUES (:api_key, :name, :email, :company, :purpose, :usage_limit, :expires_at)";

            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':api_key', $apiKey);
            $stmt->bindParam(':name', $data['name']);
            $stmt->bindParam(':email', $data['email']);
            $stmt->bindParam(':company', $data['company']);
            $stmt->bindParam(':purpose', $data['purpose']);
            $stmt->bindParam(':usage_limit', $data['usage_limit']);
            $stmt->bindParam(':expires_at', $data['expires_at']);

            if ($stmt->execute()) {
                return $apiKey;
            }
            return false;
        } catch (Exception $e) {
            error_log("Create API key error: " . $e->getMessage());
            return false;
        }
    }

    public function getAllApiKeys() {
        try {
            $query = "SELECT * FROM api_keys ORDER BY created_at DESC";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll();
        } catch (Exception $e) {
            error_log("Get all API keys error: " . $e->getMessage());
            return [];
        }
    }

    public function updateApiKeyStatus($id, $isActive) {
        try {
            $query = "UPDATE api_keys SET is_active = :is_active WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            $stmt->bindParam(':is_active', $isActive);
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Update API key status error: " . $e->getMessage());
            return false;
        }
    }

    public function deleteApiKey($id) {
        try {
            $query = "DELETE FROM api_keys WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Delete API key error: " . $e->getMessage());
            return false;
        }
    }

    public function getApiKeyUsage($apiKey) {
        try {
            $query = "SELECT COUNT(*) as usage_count FROM api_usage_logs WHERE api_key = :api_key";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':api_key', $apiKey);
            $stmt->execute();
            $result = $stmt->fetch();
            return $result['usage_count'];
        } catch (Exception $e) {
            error_log("Get API key usage error: " . $e->getMessage());
            return 0;
        }
    }
}

$apiKeyManager = new ApiKeyManager();
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $apiKey = $apiKeyManager->createApiKey([
                    'name' => $_POST['name'],
                    'email' => $_POST['email'],
                    'company' => $_POST['company'],
                    'purpose' => $_POST['purpose'],
                    'usage_limit' => (int)$_POST['usage_limit'],
                    'expires_at' => $_POST['expires_at'] ?: null
                ]);

                if ($apiKey) {
                    $message = "API Key 創建成功: " . $apiKey;
                } else {
                    $error = "API Key 創建失敗";
                }
                break;

            case 'toggle_status':
                $id = (int)$_POST['id'];
                $currentStatus = (int)$_POST['current_status'];
                $newStatus = $currentStatus ? 0 : 1;

                if ($apiKeyManager->updateApiKeyStatus($id, $newStatus)) {
                    $message = $newStatus ? "API Key 已啟用" : "API Key 已停用";
                } else {
                    $error = "狀態更新失敗";
                }
                break;

            case 'delete':
                $id = (int)$_POST['id'];
                if ($apiKeyManager->deleteApiKey($id)) {
                    $message = "API Key 已刪除";
                } else {
                    $error = "刪除失敗";
                }
                break;
        }
    }
}

$apiKeys = $apiKeyManager->getAllApiKeys();
?>

<div class="row mb-3">
    <div class="col-lg-9">
        <h4>API Key 管理</h4>
        <p class="text-muted">管理 AI Writer API 的訪問金鑰</p>
    </div>
    <div class="col-lg-3 text-end">
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createApiKeyModal">
            <i class="fas fa-plus"></i> 創建 API Key
        </button>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="fas fa-key"></i> API Keys 列表
        </h5>
    </div>
    <div class="card-body">
        <?php if (empty($apiKeys)): ?>
            <div class="text-center py-5">
                <i class="fas fa-key fa-4x text-muted mb-3"></i>
                <h5 class="text-muted">尚無 API Keys</h5>
                <p class="text-muted">創建第一個 API Key 開始使用</p>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createApiKeyModal">
                    <i class="fas fa-plus"></i> 創建 API Key
                </button>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>API Key</th>
                            <th>申請人</th>
                            <th>公司/組織</th>
                            <th>用途</th>
                            <th>使用量</th>
                            <th>狀態</th>
                            <th>創建日期</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($apiKeys as $key): ?>
                            <?php
                            $usage = $apiKeyManager->getApiKeyUsage($key['api_key']);
                            $usagePercentage = $key['usage_limit'] > 0 ? ($usage / $key['usage_limit']) * 100 : 0;
                            ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <code class="api-key-display bg-light p-2 rounded border"
                                              data-full="<?= htmlspecialchars($key['api_key']) ?>"
                                              style="cursor: pointer; user-select: none;"
                                              title="點擊複製完整 API Key">
                                            <?= htmlspecialchars(substr($key['api_key'], 0, 16)) ?>...
                                            <i class="fas fa-copy ms-1 text-muted"></i>
                                        </code>
                                        <button class="btn btn-sm btn-outline-secondary ms-2 btn-copy-effect"
                                                onclick="copyApiKey('<?= htmlspecialchars($key['api_key']) ?>', this)"
                                                title="複製 API Key">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-info ms-1"
                                                onclick="showFullApiKey('<?= htmlspecialchars($key['api_key']) ?>')"
                                                title="顯示完整 API Key">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <div>
                                        <strong><?= htmlspecialchars($key['name']) ?></strong>
                                        <br><small class="text-muted"><?= htmlspecialchars($key['email']) ?></small>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($key['company'] ?: '-') ?></td>
                                <td>
                                    <small><?= htmlspecialchars(substr($key['purpose'], 0, 50)) ?><?= strlen($key['purpose']) > 50 ? '...' : '' ?></small>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <div class="progress" style="height: 6px;">
                                                <div class="progress-bar <?= $usagePercentage > 80 ? 'bg-danger' : ($usagePercentage > 60 ? 'bg-warning' : 'bg-success') ?>"
                                                     style="width: <?= min($usagePercentage, 100) ?>%"></div>
                                            </div>
                                        </div>
                                        <small class="ms-2"><?= number_format($usage) ?>/<?= number_format($key['usage_limit']) ?></small>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($key['is_active']): ?>
                                        <span class="badge bg-success">啟用</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">停用</span>
                                    <?php endif; ?>

                                    <?php if ($key['expires_at'] && strtotime($key['expires_at']) < time()): ?>
                                        <span class="badge bg-danger">已過期</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small class="text-muted">
                                        <?= date('Y-m-d H:i', strtotime($key['created_at'])) ?>
                                    </small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="toggle_status">
                                            <input type="hidden" name="id" value="<?= $key['id'] ?>">
                                            <input type="hidden" name="current_status" value="<?= $key['is_active'] ?>">
                                            <button type="submit" class="btn btn-outline-<?= $key['is_active'] ? 'warning' : 'success' ?>"
                                                    title="<?= $key['is_active'] ? '停用' : '啟用' ?>">
                                                <i class="fas fa-<?= $key['is_active'] ? 'pause' : 'play' ?>"></i>
                                            </button>
                                        </form>

                                        <form method="POST" class="d-inline"
                                              onsubmit="return confirm('確定要刪除此 API Key 嗎？此操作無法復原。')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $key['id'] ?>">
                                            <button type="submit" class="btn btn-outline-danger" title="刪除">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- 統計卡片 -->
<div class="row mt-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">總 API Keys</h6>
                        <h3><?= count($apiKeys) ?></h3>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-key fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">啟用中</h6>
                        <h3><?= count(array_filter($apiKeys, function($k) { return $k['is_active']; })) ?></h3>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-check-circle fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">今日請求</h6>
                        <h3>
                            <?php
                            try {
                                $database = new Database();
                                $db = $database->getConnection();
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM api_usage_logs WHERE DATE(used_at) = CURDATE()");
                                $stmt->execute();
                                $result = $stmt->fetch();
                                echo number_format($result['count']);
                            } catch (Exception $e) {
                                echo '0';
                            }
                            ?>
                        </h3>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-chart-line fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">總請求數</h6>
                        <h3>
                            <?php
                            try {
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM api_usage_logs");
                                $stmt->execute();
                                $result = $stmt->fetch();
                                echo number_format($result['count']);
                            } catch (Exception $e) {
                                echo '0';
                            }
                            ?>
                        </h3>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-database fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 創建 API Key Modal -->
<div class="modal fade" id="createApiKeyModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">創建新 API Key</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="create">

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="name" class="form-label">申請人姓名 *</label>
                                <input type="text" class="form-control" id="name" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="email" class="form-label">電子郵件 *</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="company" class="form-label">公司/組織</label>
                        <input type="text" class="form-control" id="company" name="company">
                    </div>

                    <div class="mb-3">
                        <label for="purpose" class="form-label">使用用途 *</label>
                        <textarea class="form-control" id="purpose" name="purpose" rows="3"
                                  placeholder="請詳細說明 API 的使用用途..." required></textarea>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="usage_limit" class="form-label">使用限制</label>
                                <select class="form-select" id="usage_limit" name="usage_limit">
                                    <option value="1000">1,000 次/月</option>
                                    <option value="5000">5,000 次/月</option>
                                    <option value="10000">10,000 次/月</option>
                                    <option value="50000">50,000 次/月</option>
                                    <option value="100000">100,000 次/月</option>
                                    <option value="-1">無限制</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="expires_at" class="form-label">過期日期</label>
                                <input type="date" class="form-control" id="expires_at" name="expires_at">
                                <small class="form-text text-muted">留空表示永不過期</small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">創建 API Key</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.api-key-display:hover {
    background-color: #e9ecef !important;
    border-color: #007bff !important;
}

.api-key-display {
    transition: all 0.2s ease-in-out;
}

.copy-toast {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.btn-copy-effect {
    position: relative;
    overflow: hidden;
}

.btn-copy-effect::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    background: rgba(255, 255, 255, 0.4);
    border-radius: 50%;
    transform: translate(-50%, -50%);
    transition: width 0.3s, height 0.3s;
}

.btn-copy-effect.clicked::after {
    width: 100px;
    height: 100px;
}
</style>

<script>
function copyApiKey(apiKey, buttonElement) {
    // Add visual feedback to the button
    if (buttonElement && buttonElement.classList) {
        buttonElement.classList.add('btn-copy-effect', 'clicked');
        setTimeout(() => {
            buttonElement.classList.remove('clicked');
        }, 300);
    }

    // Try modern clipboard API first
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(apiKey).then(function() {
            showCopySuccess();
        }).catch(function(err) {
            console.error('Clipboard API failed:', err);
            fallbackCopy(apiKey);
        });
    } else {
        // Fallback for older browsers or non-secure contexts
        fallbackCopy(apiKey);
    }
}

function fallbackCopy(text) {
    // Create a temporary textarea element
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.left = '-999999px';
    textarea.style.top = '-999999px';
    document.body.appendChild(textarea);

    try {
        textarea.focus();
        textarea.select();
        const successful = document.execCommand('copy');
        if (successful) {
            showCopySuccess();
        } else {
            showCopyError();
        }
    } catch (err) {
        console.error('Fallback copy failed:', err);
        showCopyError();
    } finally {
        document.body.removeChild(textarea);
    }
}

function showCopySuccess() {
    // Remove any existing toasts first
    const existingToasts = document.querySelectorAll('.copy-toast');
    existingToasts.forEach(toast => toast.remove());

    // Create success toast with better styling
    const toast = document.createElement('div');
    toast.className = 'copy-toast alert alert-success alert-dismissible fade show position-fixed';
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        <i class="fas fa-check-circle me-2"></i>
        <strong>成功！</strong> API Key 已複製到剪貼簿
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;

    document.body.appendChild(toast);

    // Auto remove after 3 seconds
    setTimeout(() => {
        if (toast.parentNode) {
            toast.remove();
        }
    }, 3000);
}

function showCopyError() {
    // Remove any existing toasts first
    const existingToasts = document.querySelectorAll('.copy-toast');
    existingToasts.forEach(toast => toast.remove());

    // Create error toast
    const toast = document.createElement('div');
    toast.className = 'copy-toast alert alert-warning alert-dismissible fade show position-fixed';
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        <i class="fas fa-exclamation-triangle me-2"></i>
        <strong>提示：</strong> 請手動選擇並複製 API Key
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;

    document.body.appendChild(toast);

    // Auto remove after 5 seconds
    setTimeout(() => {
        if (toast.parentNode) {
            toast.remove();
        }
    }, 5000);
}

function showFullApiKey(apiKey) {
    // Remove any existing modals first
    const existingModal = document.getElementById('apiKeyModal');
    if (existingModal) {
        existingModal.remove();
    }

    // Create modal to show full API key
    const modal = document.createElement('div');
    modal.id = 'apiKeyModal';
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-key"></i> 完整 API Key
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        請安全保存此 API Key，不要在公開場合分享
                    </div>
                    <div class="form-group">
                        <label class="form-label">API Key:</label>
                        <div class="input-group">
                            <input type="text" class="form-control font-monospace"
                                   id="fullApiKeyInput" value="${apiKey}" readonly>
                            <button class="btn btn-outline-secondary btn-copy-effect" type="button"
                                    onclick="copyApiKey('${apiKey}', this)">
                                <i class="fas fa-copy"></i> 複製
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">關閉</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // Show modal using Bootstrap
    const bootstrapModal = new bootstrap.Modal(modal);
    bootstrapModal.show();

    // Auto-select the API key text for easy copying
    const input = modal.querySelector('#fullApiKeyInput');
    input.focus();
    input.select();

    // Remove modal from DOM when hidden
    modal.addEventListener('hidden.bs.modal', function() {
        modal.remove();
    });
}

// Enhance API key display with better copy functionality
document.addEventListener('DOMContentLoaded', function() {
    // Set minimum date to today for expiration date
    const expiresField = document.getElementById('expires_at');
    if (expiresField) {
        expiresField.min = new Date().toISOString().split('T')[0];
    }

    // Add click-to-copy functionality to API key displays
    document.querySelectorAll('.api-key-display').forEach(function(element) {
        element.style.cursor = 'pointer';
        element.title = '點擊複製完整 API Key';

        element.addEventListener('click', function() {
            const fullApiKey = this.getAttribute('data-full');
            if (fullApiKey) {
                copyApiKey(fullApiKey);
            }
        });
    });
});
</script>