<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 1. Security & Database
include 'db.php'; 

if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// 2. Fetch User Data
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

$api_status = $user['api_status'] ?? 'none'; // none, pending, active
$base_url = "https://Nagarta.wisehivesphere.com/api/v1/" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']) . "/api/v1/";

// 3. Handle Access Request
$msg = "";
if (isset($_POST['request_access'])) {
    // Check if not already pending or active
    if ($api_status == 'none') {
        // Generate a key but keep status pending (Optional: or just set status pending and generate key later)
        $new_key = "sk_" . bin2hex(random_bytes(16));
        
        $update = $conn->prepare("UPDATE users SET api_status = 'pending', api_key = ? WHERE id = ?");
        $update->bind_param("si", $new_key, $user_id);
        
        if ($update->execute()) {
            $api_status = 'pending';
            $msg = "Request submitted successfully! Admin will review shortly.";
        } else {
            $msg = "Error submitting request.";
        }
    }
}

// 4. Handle Key Reset (Only for Active Users)
if (isset($_POST['reset_key']) && $api_status == 'active') {
    $new_key = "sk_" . bin2hex(random_bytes(16));
    $update = $conn->prepare("UPDATE users SET api_key = ? WHERE id = ?");
    $update->bind_param("si", $new_key, $user_id);
    if($update->execute()) {
        $user['api_key'] = $new_key; // Update variable for display
        $msg = "New API Key generated successfully.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Developer API - Nagarta Data</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2563eb;
            --secondary: #1e293b;
            --bg: #f1f5f9;
            --white: #ffffff;
            --text: #334155;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background: var(--bg); display: flex; height: 100vh; overflow: hidden; }

        /* Sidebar (Same as Dashboard) */
        .sidebar { width: 250px; background: var(--secondary); color: var(--white); display: flex; flex-direction: column; transition: 0.3s; }
        .sidebar-header { padding: 20px; font-size: 1.5rem; font-weight: bold; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .nav-links { list-style: none; padding: 20px 0; flex: 1; }
        .nav-links li a { display: flex; align-items: center; padding: 15px 25px; color: #cbd5e1; text-decoration: none; transition: 0.3s; }
        .nav-links li a:hover, .nav-links li a.active { background: rgba(255,255,255,0.1); color: var(--white); border-left: 4px solid var(--primary); }
        .nav-links li a i { margin-right: 15px; width: 20px; }

        /* Main Content */
        .main-content { flex: 1; overflow-y: auto; padding: 20px; }
        .top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; background: var(--white); padding: 15px 25px; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); }

        /* API Content Styles */
        .api-card { background: white; padding: 30px; border-radius: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); margin-bottom: 30px; }
        .api-card h3 { margin-bottom: 15px; color: var(--secondary); }
        
        .status-badge { padding: 8px 15px; border-radius: 30px; font-weight: 600; font-size: 0.9rem; display: inline-block; margin-bottom: 15px; }
        .status-active { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-none { background: #f1f5f9; color: #64748b; }

        .key-box { 
            background: var(--secondary); color: #10b981; padding: 15px; border-radius: 10px; 
            font-family: monospace; font-size: 1.1rem; letter-spacing: 1px; 
            display: flex; justify-content: space-between; align-items: center; word-break: break-all;
        }
        
        .code-block { background: #1e293b; color: #e2e8f0; padding: 20px; border-radius: 10px; overflow-x: auto; margin: 15px 0; font-family: monospace; }
        .endpoint { background: #f1f5f9; padding: 5px 10px; border-radius: 5px; color: #d63384; font-weight: bold; font-family: monospace; }

        .btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; transition: 0.3s; text-decoration: none; display: inline-block; }
        .btn-primary { background: var(--primary); color: white; }
        .btn-danger { background: var(--danger); color: white; }
        .btn:hover { opacity: 0.9; transform: translateY(-1px); }

        /* Mobile Toggle */
        .menu-toggle { display: none; font-size: 1.5rem; cursor: pointer; }
        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -250px; height: 100%; z-index: 999; }
            .sidebar.active { left: 0; }
            .menu-toggle { display: block; }
        }
    </style>
</head>
<body>

    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">Nagarta Data</div>
        <ul class="nav-links">
            <li><a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a></li>
            <li><a href="dashboard.php"><i class="fas fa-wifi"></i> Buy Data</a></li>
            <li><a href="transactions.php"><i class="fas fa-history"></i> Transactions</a></li>
            <li><a href="developer.php" class="active"><i class="fas fa-code"></i> Developer API</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="top-bar">
            <div class="menu-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
            <h3>Developer API</h3>
            <div><?php echo htmlspecialchars($user['username']); ?></div>
        </div>

        <?php if(!empty($msg)): ?>
            <div style="background: #dcfce7; color: #166534; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
                <?php echo $msg; ?>
            </div>
        <?php endif; ?>

        <div class="api-card">
            <h3>API Access Status</h3>
            
            <?php if ($api_status == 'active'): ?>
                <span class="status-badge status-active"><i class="fas fa-check-circle"></i> Active</span>
                <p style="margin-bottom: 10px; color: #64748b;">Use this key to authenticate your API requests. Keep it secret.</p>
                
                <div class="key-box">
                    <span id="apiKey"><?php echo $user['api_key']; ?></span>
                    <i class="fas fa-copy" style="cursor: pointer; color: white;" onclick="copyKey()" title="Copy Key"></i>
                </div>

                <div style="margin-top: 20px;">
                    <form method="POST" onsubmit="return confirm('Are you sure? Your old key will stop working immediately.')">
                        <button type="submit" name="reset_key" class="btn btn-danger">Reset API Key</button>
                    </form>
                </div>

            <?php elseif ($api_status == 'pending'): ?>
                <span class="status-badge status-pending"><i class="fas fa-clock"></i> Pending Approval</span>
                <p>Your request for API access has been received. Our team is reviewing your account.</p>
                <p style="margin-top: 10px;">You will be notified once approved.</p>

            <?php else: ?>
                <span class="status-badge status-none"><i class="fas fa-lock"></i> Not Active</span>
                <p>You currently do not have access to our Developer API.</p>
                <p style="margin-bottom: 20px;">API access allows you to integrate our services directly into your own website or app.</p>
                
                <form method="POST">
                    <button type="submit" name="request_access" class="btn btn-primary">Request API Access</button>
                </form>
            <?php endif; ?>
        </div>

        <?php if ($api_status == 'active'): ?>
        <div class="api-card">
            <h3>Integration Guide</h3>
            <p>Base URL: <span class="endpoint"><?php echo $base_url; ?></span></p>

            <h4 style="margin-top: 20px; color: var(--primary);">1. Check Balance</h4>
            <p>Get your current wallet balance.</p>
            <div class="code-block">
GET /user
Authorization: Token <?php echo $user['api_key']; ?>
            </div>

            <h4 style="margin-top: 20px; color: var(--primary);">2. Purchase Data</h4>
            <p>Send a POST request to purchase data.</p>
            <div class="code-block">
POST /data
Authorization: Token <?php echo $user['api_key']; ?>
Content-Type: application/json

{
    "network": "MTN",
    "mobile_number": "08012345678",
    "plan": "195" 
}
            </div>
            
            <h4 style="margin-top: 20px; color: var(--primary);">3. Server Response</h4>
            <div class="code-block">
{
    "status": "success",
    "message": "Data delivered successfully",
    "reference": "API1756281928"
}
            </div>

            <div style="margin-top: 30px;">
                <a href="#" class="btn btn-primary"><i class="fas fa-download"></i> Download Full PDF Documentation</a>
            </div>
        </div>
        <?php endif; ?>

    </div>

    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
        }

        function copyKey() {
            var copyText = document.getElementById("apiKey");
            navigator.clipboard.writeText(copyText.innerText);
            alert("API Key Copied!");
        }
    </script>
</body>
</html>