<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['super_admin', 'system_admin'])) {
    header("Location: login.php");
    exit();
}

include '../includes/db.php';
include 'includes/header.php';

$message = "";

// Handle API Key Generation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_api_key'])) {
    $portal_name = $conn->real_escape_string($_POST['portal_name']);
    $description = $conn->real_escape_string($_POST['description']);
    
    // Generate unique API key
    $api_key = 'AK_' . strtoupper(uniqid()) . '_' . bin2hex(random_bytes(16));
    
    $sql = "INSERT INTO api_keys (portal_name, description, api_key, generated_by, status) 
            VALUES ('$portal_name', '$description', '$api_key', {$_SESSION['user_id']}, 'active')";
    
    if ($conn->query($sql) === TRUE) {
        $message = "API key generated successfully: $api_key";
    } else {
        $message = "Error generating API key: " . $conn->error;
    }
}

// Handle API Key Deactivation
if (isset($_GET['deactivate']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $sql = "UPDATE api_keys SET status = 'inactive' WHERE id = $id";
    $conn->query($sql);
    header("Location: portal_integration.php");
    exit();
}

// Get API Keys
$api_keys_sql = "SELECT ak.*, u.full_name as generated_by_name 
                 FROM api_keys ak
                 JOIN users u ON ak.generated_by = u.id
                 ORDER BY ak.created_at DESC";
$api_keys_result = $conn->query($api_keys_sql);
?>

<div class="dashboard-container">
    <div class="sidebar admin-sidebar">
        <?php include 'includes/sidebar.php'; ?>
    </div>

    <div class="main-content">
        <h2>Portal Integration</h2>
        
        <?php if($message): ?>
            <div class="alert alert-info">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Generate API Key</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <div class="form-group">
                        <label>Portal Name</label>
                        <input type="text" name="portal_name" class="form-control" placeholder="e.g., Student Portal, LMS System" required>
                        <small>Enter the name of the external system that will integrate with this admission portal</small>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="Describe the integration purpose"></textarea>
                    </div>
                    <button type="submit" name="generate_api_key" class="btn-primary">Generate API Key</button>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">API Documentation</h3>
            </div>
            <div class="card-body">
                <h4>Available Endpoints</h4>
                
                <div class="endpoint-section">
                    <h5>1. Get Student Applications</h5>
                    <code>GET /api/applications</code>
                    <p>Retrieve all student applications with filtering options</p>
                    <strong>Parameters:</strong>
                    <ul>
                        <li>status (optional): Filter by application status (submitted, under_review, approved, rejected)</li>
                        <li>program_id (optional): Filter by program ID</li>
                        <li>limit (optional): Number of results to return (default: 50)</li>
                    </ul>
                </div>

                <div class="endpoint-section">
                    <h5>2. Get Application Details</h5>
                    <code>GET /api/applications/{id}</code>
                    <p>Get detailed information about a specific application</p>
                </div>

                <div class="endpoint-section">
                    <h5>3. Update Application Status</h5>
                    <code>PUT /api/applications/{id}/status</code>
                    <p>Update application status and add comments</p>
                    <strong>Request Body:</strong>
                    <pre>
{
    "status": "approved",
    "comments": "Application approved for admission"
}
                    </pre>
                </div>

                <div class="endpoint-section">
                    <h5>4. Get Programs</h5>
                    <code>GET /api/programs</code>
                    <p>Retrieve all available programs</p>
                </div>

                <div class="endpoint-section">
                    <h5>Authentication</h5>
                    <p>Include the API key in the request header:</p>
                    <code>Authorization: Bearer YOUR_API_KEY</code>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Generated API Keys</h3>
            </div>
            <div class="card-body">
                <table>
                    <thead>
                        <tr>
                            <th>Portal Name</th>
                            <th>Description</th>
                            <th>API Key</th>
                            <th>Status</th>
                            <th>Generated At</th>
                            <th>Generated By</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($api_keys_result->num_rows > 0): ?>
                            <?php while($key = $api_keys_result->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo $key['portal_name']; ?></td>
                                    <td><?php echo $key['description'] ?: 'N/A'; ?></td>
                                    <td>
                                        <code style="background: #f5f5f5; padding: 2px 6px; border-radius: 3px;">
                                            <?php echo $key['api_key']; ?>
                                        </code>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo $key['status'] == 'active' ? 'badge-success' : 'badge-danger'; ?>">
                                            <?php echo ucfirst($key['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('M d, Y H:i', strtotime($key['created_at'])); ?></td>
                                    <td><?php echo $key['generated_by_name']; ?></td>
                                    <td>
                                        <?php if($key['status'] == 'active'): ?>
                                            <a href="?deactivate=1&id=<?php echo $key['id']; ?>" 
                                               class="btn-danger" style="padding: 5px 10px; font-size: 0.9rem;"
                                               onclick="return confirm('Are you sure you want to deactivate this API key?')">Deactivate</a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" style="text-align: center;">No API keys generated yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
