<?php
session_start();

if (!isset($_SESSION['admin']) || $_SESSION['admin'] !== true) {
    header('Location: admin-login.php');
    exit;
}

$host = 'localhost:3306';
$dbname = 'gqdcvggs_traffic';
$username = 'gqdcvggs';
$password = 'imaors_management.346980*#@-onlyforcpanel;forchange';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'create') {
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';
        
        if (empty($name) || empty($email)) {
            $message = 'Name and email are required';
            $messageType = 'error';
        } else {
            $api_key = generateApiKey();
            
            try {
                $stmt = $pdo->prepare("INSERT INTO api_keys (api_key, name, email, created_at, active) VALUES (?, ?, ?, NOW(), 1)");
                $stmt->execute([$api_key, $name, $email]);
                
                $message = 'API key created successfully';
                $messageType = 'success';
            } catch (PDOException $e) {
                $message = 'Failed to create API key: ' . $e->getMessage();
                $messageType = 'error';
            }
        }
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'toggle') {
        $id = $_POST['id'] ?? 0;
        $active = $_POST['active'] === '1' ? 0 : 1;
        
        try {
            $stmt = $pdo->prepare("UPDATE api_keys SET active = ? WHERE id = ?");
            $stmt->execute([$active, $id]);
            
            $message = 'API key status updated';
            $messageType = 'success';
        } catch (PDOException $e) {
            $message = 'Failed to update API key: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $id = $_POST['id'] ?? 0;
        
        try {
            $stmt = $pdo->prepare("DELETE FROM api_keys WHERE id = ?");
            $stmt->execute([$id]);
            
            $message = 'API key deleted';
            $messageType = 'success';
        } catch (PDOException $e) {
            $message = 'Failed to delete API key: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
}

try {
    $stmt = $pdo->query("SELECT * FROM api_keys ORDER BY created_at DESC");
    $api_keys = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $message = 'Failed to fetch API keys: ' . $e->getMessage();
    $messageType = 'error';
    $api_keys = [];
}

function generateApiKey() {
    return bin2hex(random_bytes(16));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Key Manager - TrafficLight</title>
    <link rel="icon" type="image/png" href="traffic_logo.png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'sans': ['Inter', 'sans-serif']
                    },
                    colors: {
                        primary: {
                            50: '#f0f9ff',
                            100: '#e0f2fe',
                            200: '#bae6fd',
                            300: '#7dd3fc',
                            400: '#38bdf8',
                            500: '#0ea5e9',
                            600: '#0284c7',
                            700: '#0369a1',
                            800: '#075985',
                            900: '#0c4a6e'
                        },
                        traffic: {
                            red: '#ef4444',
                            green: '#10b981',
                            amber: '#f59e0b'
                        }
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50">
    <header class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <img src="traffic_logo.png" alt="Logo" class="w-8 h-8 mr-2">
                    <h1 class="text-xl font-semibold text-gray-800">TrafficLight Systems API</h1>
                </div>
                <div class="flex items-center">
                    <a href="./api-documentation" class="text-gray-600 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium">Documentation</a>
                    <a href="/api-key-manager" class="text-primary-600 hover:text-primary-700 px-3 py-2 rounded-md text-sm font-medium">API Keys</a>
                    <a href="admin-logout.php" class="text-gray-600 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium">Logout</a>
                </div>
            </div>
        </div>
    </header>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div class="md:flex md:items-center md:justify-between mb-6">
            <div class="flex-1 min-w-0">
                <h2 class="text-2xl font-bold leading-7 text-gray-900 sm:text-3xl sm:truncate">API Key Management</h2>
                <p class="mt-1 text-sm text-gray-500">Create and manage API keys for TrafficLight API access</p>
            </div>
            <div class="mt-4 flex md:mt-0 md:ml-4">
                <button type="button" id="createKeyBtn" class="ml-3 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                    <i class="fas fa-plus -ml-1 mr-2"></i>
                    Create API Key
                </button>
            </div>
        </div>

        <?php if (!empty($message)): ?>
            <div class="rounded-md <?php echo $messageType === 'success' ? 'bg-green-50' : 'bg-red-50'; ?> p-4 mb-6">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <?php if ($messageType === 'success'): ?>
                            <i class="fas fa-check-circle text-green-400"></i>
                        <?php else: ?>
                            <i class="fas fa-exclamation-circle text-red-400"></i>
                        <?php endif; ?>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium <?php echo $messageType === 'success' ? 'text-green-800' : 'text-red-800'; ?>">
                            <?php echo $message; ?>
                        </p>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="bg-white shadow overflow-hidden sm:rounded-md">
            <?php if (empty($api_keys)): ?>
                <div class="p-8 text-center">
                    <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-gray-100">
                        <i class="fas fa-key text-gray-400"></i>
                    </div>
                    <h3 class="mt-2 text-sm font-medium text-gray-900">No API keys</h3>
                    <p class="mt-1 text-sm text-gray-500">Create your first API key to allow external access to the TrafficLight API.</p>
                    <div class="mt-6">
                        <button type="button" onclick="document.getElementById('createKeyBtn').click()" class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                            <i class="fas fa-plus -ml-1 mr-2"></i>
                            New API Key
                        </button>
                    </div>
                </div>
            <?php else: ?>
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name / Email</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">API Key</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($api_keys as $key): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($key['name']); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($key['email']); ?></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center">
                                        <div class="text-sm font-mono text-gray-900 truncate max-w-xs"><?php echo htmlspecialchars($key['api_key']); ?></div>
                                        <button type="button" class="copy-btn ml-2 text-gray-400 hover:text-gray-600" data-clipboard-text="<?php echo htmlspecialchars($key['api_key']); ?>">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <?php echo date('M j, Y', strtotime($key['created_at'])); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $key['active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                        <?php echo $key['active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <form method="POST" class="inline-block mr-2">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id" value="<?php echo $key['id']; ?>">
                                        <input type="hidden" name="active" value="<?php echo $key['active']; ?>">
                                        <button type="submit" class="text-primary-600 hover:text-primary-900">
                                            <?php echo $key['active'] ? 'Deactivate' : 'Activate'; ?>
                                        </button>
                                    </form>
                                    <form method="POST" class="inline-block delete-form">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $key['id']; ?>">
                                        <button type="submit" class="text-traffic-red hover:text-red-700">
                                            Delete
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </main>

    <div id="createKeyModal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form method="POST">
                    <input type="hidden" name="action" value="create">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <div class="sm:flex sm:items-start">
                            <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-primary-100 sm:mx-0 sm:h-10 sm:w-10">
                                <i class="fas fa-key text-primary-600"></i>
                            </div>
                            <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                                <h3 class="text-lg leading-6 font-medium text-gray-900">
                                    Create API Key
                                </h3>
                                <div class="mt-4 space-y-4">
                                    <div>
                                        <label for="name" class="block text-sm font-medium text-gray-700">Application Name</label>
                                        <input type="text" name="name" id="name" class="mt-1 focus:ring-primary-500 focus:border-primary-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md" required>
                                    </div>
                                    <div>
                                        <label for="email" class="block text-sm font-medium text-gray-700">Developer Email</label>
                                        <input type="email" name="email" id="email" class="mt-1 focus:ring-primary-500 focus:border-primary-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md" required>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:ml-3 sm:w-auto sm:text-sm">
                            Create
                        </button>
                        <button type="button" id="cancelCreateKey" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const createKeyBtn = document.getElementById('createKeyBtn');
            const createKeyModal = document.getElementById('createKeyModal');
            const cancelCreateKey = document.getElementById('cancelCreateKey');
            
            createKeyBtn.addEventListener('click', function() {
                createKeyModal.classList.remove('hidden');
            });
            
            cancelCreateKey.addEventListener('click', function() {
                createKeyModal.classList.add('hidden');
            });
            
            const deleteForms = document.querySelectorAll('.delete-form');
            deleteForms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    if (!confirm('Are you sure you want to delete this API key? This action cannot be undone.')) {
                        e.preventDefault();
                    }
                });
            });
            
            const clipboard = new ClipboardJS('.copy-btn');
            clipboard.on('success', function(e) {
                const originalIcon = e.trigger.innerHTML;
                e.trigger.innerHTML = '<i class="fas fa-check"></i>';
                
                setTimeout(function() {
                    e.trigger.innerHTML = originalIcon;
                }, 1500);
                
                e.clearSelection();
            });
        });
    </script>
</body>
</html>