<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

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

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

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';

// Handle API key actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['create_api_key'])) {
        $name = trim($_POST['name'] ?? '');
        $permissions = $_POST['permissions'] ?? [];
        
        if (empty($name)) {
            $error = "API key name is required.";
        } else {
            try {
                // Generate a secure API key
                $api_key = 'jv_' . bin2hex(random_bytes(24));
                
                // Store the hashed key in database (never store plain text)
                $hashed_key = password_hash($api_key, PASSWORD_DEFAULT);
                
                $stmt = $pdo->prepare("INSERT INTO api_keys (
                    name, key_hash, permissions, status, created_by, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                
                $stmt->execute([
                    $name,
                    $hashed_key,
                    json_encode($permissions),
                    'active',
                    $_SESSION['user_id']
                ]);
                
                $key_id = $pdo->lastInsertId();
                
                // Store the plain text key temporarily to display to user
                $_SESSION['new_api_key'] = $api_key;
                $_SESSION['new_api_key_name'] = $name;
                
                // Log the activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute([
                    $_SESSION['user_id'],
                    "api_key_created",
                    "Admin {$admin['first_name']} {$admin['last_name']} created API key: {$name}"
                ]);
                
                $success = "API key created successfully!";
            } catch (Exception $e) {
                $error = "Failed to create API key: " . $e->getMessage();
            }
        }
    }
    
    if (isset($_POST['revoke_api_key'])) {
        $key_id = $_POST['key_id'];
        
        try {
            $stmt = $pdo->prepare("UPDATE api_keys SET status = 'revoked', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$key_id]);
            
            $success = "API key revoked successfully!";
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "api_key_revoked",
                "Admin {$admin['first_name']} {$admin['last_name']} revoked an API key"
            ]);
        } catch (Exception $e) {
            $error = "Failed to revoke API key: " . $e->getMessage();
        }
    }
    
    if (isset($_POST['regenerate_api_key'])) {
        $key_id = $_POST['key_id'];
        
        try {
            // Generate new key
            $new_api_key = 'jv_' . bin2hex(random_bytes(24));
            $new_hashed_key = password_hash($new_api_key, PASSWORD_DEFAULT);
            
            $stmt = $pdo->prepare("UPDATE api_keys SET key_hash = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_hashed_key, $key_id]);
            
            // Store the plain text key temporarily to display to user
            $_SESSION['new_api_key'] = $new_api_key;
            $_SESSION['new_api_key_name'] = 'Regenerated Key';
            
            $success = "API key regenerated successfully!";
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "api_key_regenerated",
                "Admin {$admin['first_name']} {$admin['last_name']} regenerated an API key"
            ]);
        } catch (Exception $e) {
            $error = "Failed to regenerate API key: " . $e->getMessage();
        }
    }
}

// Get API keys
$stmt = $pdo->prepare("SELECT ak.*, CONCAT(a.first_name, ' ', a.last_name) as created_by_name 
                      FROM api_keys ak
                      LEFT JOIN admins a ON ak.created_by = a.id
                      ORDER BY ak.created_at DESC");
$stmt->execute();
$api_keys = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>API Keys - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-active {
            background: #28a745;
            color: white;
        }
        .status-revoked {
            background: #dc3545;
            color: white;
        }
        .key-display {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 1.1em;
            word-break: break-all;
            margin: 10px 0;
        }
        .permission-tag {
            display: inline-block;
            padding: 3px 8px;
            background: #3fb7fe;
            color: white;
            border-radius: 15px;
            font-size: 0.8em;
            margin: 2px;
        }
    </style>
</head>
<body>
    <?php include 'admin-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="section-title position-relative mb-4">
            <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Integration</h6>
            <h1 class="display-5">API Key Management</h1>
        </div>
        
        <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['new_api_key']) && isset($_SESSION['new_api_key_name'])): ?>
        <div class="alert alert-info">
            <h5>API Key Created: <?= htmlspecialchars($_SESSION['new_api_key_name']) ?></h5>
            <p><strong>API Key:</strong></p>
            <div class="key-display">
                <?= htmlspecialchars($_SESSION['new_api_key']) ?>
            </div>
            <p class="text-danger"><strong>Important:</strong> Copy this key now! It will not be shown again for security reasons.</p>
            <button class="btn btn-sm btn-secondary" onclick="copyToClipboard()">Copy to Clipboard</button>
            <script>
                function copyToClipboard() {
                    const key = document.querySelector('.key-display').innerText;
                    navigator.clipboard.writeText(key).then(() => {
                        alert('API key copied to clipboard!');
                    });
                }
            </script>
        </div>
        <?php 
            unset($_SESSION['new_api_key']);
            unset($_SESSION['new_api_key_name']);
            endif; 
        ?>
        
        <!-- Create New API Key -->
        <div class="bg-white p-4 rounded mb-4">
            <h5 class="mb-3">Create New API Key</h5>
            <form method="POST">
                <div class="form-group">
                    <label>Key Name *</label>
                    <input type="text" name="name" class="form-control" placeholder="e.g., University Portal Integration" required>
                    <small class="form-text text-muted">A descriptive name for your API key</small>
                </div>
                
                <div class="form-group">
                    <label>Permissions</label>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="permissions[]" value="read_students" id="read_students">
                                <label class="custom-control-label" for="read_students">Read Students</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="permissions[]" value="write_students" id="write_students">
                                <label class="custom-control-label" for="write_students">Write Students</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="permissions[]" value="read_applications" id="read_applications">
                                <label class="custom-control-label" for="read_applications">Read Applications</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="permissions[]" value="write_applications" id="write_applications">
                                <label class="custom-control-label" for="write_applications">Write Applications</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="permissions[]" value="read_visa" id="read_visa">
                                <label class="custom-control-label" for="read_visa">Read Visa</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="permissions[]" value="write_visa" id="write_visa">
                                <label class="custom-control-label" for="write_visa">Write Visa</label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <button type="submit" name="create_api_key" class="btn btn-primary">Create API Key</button>
            </form>
        </div>
        
        <!-- API Keys Table -->
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Key ID</th>
                        <th>Created By</th>
                        <th>Permissions</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($api_keys)): ?>
                    <tr>
                        <td colspan="7" class="text-center">No API keys found.</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($api_keys as $key): ?>
                    <tr>
                        <td><?= htmlspecialchars($key['name']) ?></td>
                        <td>API-<?= str_pad($key['id'], 6, '0', STR_PAD_LEFT) ?></td>
                        <td><?= htmlspecialchars($key['created_by_name'] ?? 'System') ?></td>
                        <td>
                            <?php 
                            $permissions = json_decode($key['permissions'], true) ?: [];
                            foreach ($permissions as $permission): 
                            ?>
                                <span class="permission-tag"><?= htmlspecialchars(str_replace('_', ' ', $permission)) ?></span>
                            <?php endforeach; ?>
                        </td>
                        <td>
                            <span class="status-badge status-<?= strtolower($key['status']) ?>">
                                <?= ucfirst($key['status']) ?>
                            </span>
                        </td>
                        <td><?= date('M j, Y', strtotime($key['created_at'])) ?></td>
                        <td>
                            <div class="btn-group">
                                <?php if ($key['status'] === 'active'): ?>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="key_id" value="<?= $key['id'] ?>">
                                    <button type="submit" name="regenerate_api_key" class="btn btn-sm btn-warning" onclick="return confirm('Are you sure you want to regenerate this API key? This will invalidate the current key.')">Regenerate</button>
                                </form>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="key_id" value="<?= $key['id'] ?>">
                                    <button type="submit" name="revoke_api_key" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to revoke this API key? This cannot be undone.')">Revoke</button>
                                </form>
                                <?php else: ?>
                                <span class="text-muted">Revoked</span>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- API Documentation -->
        <div class="mt-5">
            <div class="bg-white p-4 rounded">
                <h5><i class="fas fa-book mr-2"></i> API Documentation</h5>
                <p>Use your API key to access our REST API endpoints. Include the key in the Authorization header:</p>
                <div class="key-display">
                    Authorization: Bearer YOUR_API_KEY
                </div>
                <p>Available endpoints:</p>
                <ul>
                    <li><code>GET /api/students</code> - Retrieve student data</li>
                    <li><code>POST /api/applications</code> - Create new applications</li>
                    <li><code>GET /api/visa-applications</code> - Retrieve visa application status</li>
                    <li><code>POST /api/messages</code> - Send messages to students</li>
                </ul>
                <p class="text-muted"><strong>Note:</strong> API keys should be kept secure and never exposed in client-side code.</p>
            </div>
        </div>
    </div>

    <?php include 'footer.php'; ?>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
</body>
</html>