<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'database.php';

if (!isset($_SESSION['username'])) {
    header('Location: ../adminx');
    exit;
}

$username = "";
$apiKey = "";
$type = "";
$limit = "";
$expiryDate = "";
$error = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['username'], $_POST['apiKey'], $_POST['type'], $_POST['Limit'], $_POST['expiryDate'])) {
        $username = trim($_POST['username']);
        $apiKey = trim($_POST['apiKey']);
        $type = trim($_POST['type']);
        $limit = trim($_POST['Limit']);
        $expiryDate = trim($_POST['expiryDate']);

        // Handle UNLIMITED
        if (strtoupper($limit) === "UNLIMITED") {
            $limit = 99999999;
        }

        if (!empty($username) && !empty($apiKey) && !empty($type) && is_numeric($limit) && !empty($expiryDate)) {
            $timezone = new DateTimeZone('Asia/Dhaka');
            $date = new DateTime('now', $timezone);
            $createDate = $date->format('Y-m-d H:i:s');

            $sql = "INSERT INTO users (username, apiKey, type, status, createDate, expiryDate, `limit`, balance, used)
                    VALUES (?, ?, ?, 'on', ?, ?, ?, ?, 0)";

            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "sssssii", $username, $apiKey, $type, $createDate, $expiryDate, $limit, $limit);

                if (mysqli_stmt_execute($stmt)) {
                    $success = "Key Added Successfully!";
                    $username = $apiKey = $type = $limit = $expiryDate = "";
                } else {
                    $error = "Database error: " . mysqli_stmt_error($stmt);
                }

                mysqli_stmt_close($stmt);
            } else {
                $error = "SQL preparation failed: " . mysqli_error($conn);
            }
        } else {
            $error = "Please fill in all fields correctly.";
        }
    } else {
        $error = "Invalid request. Missing fields.";
    }

    mysqli_close($conn);
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Key - Key Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <link href="style/common.css" rel="stylesheet">
    <style>
        .ckbutton {
            transform: translateY(-5px);
        }
        .add-key-container {
            background-color: #ffffff;
            padding: 20px;
            border-radius: 10px;
            margin: 25px auto;
            max-width: 600px;
            box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
        }
        .add-key-container h1 {
            color: #343a40;
            margin-bottom: 20px;
            text-align: center;
        }
        .form-control {
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            color: #343a40;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 10px;
        }
        .form-control::placeholder {
            color: #6c757d;
            opacity: 0.8;
        }
        .btn-primary {
            background-color: #007bff;
            border: none;
            border-radius: 5px;
            padding: 10px;
            cursor: pointer;
            font-size: 1rem;
            display: block;
            width: 100%;
            text-align: center;
        }
        .btn-primary:hover {
            background-color: #0056b3;
        }
        .btn-generate, .btn-unlimited {
            background-color: #007bff;
            border: none;
            border-radius: 5px;
            padding: 10px;
            cursor: pointer;
            font-size: 1rem;
            margin-left: 10px;
            height: 100%;
            color: #ffffff;
        }
        .btn-generate:hover, .btn-unlimited:hover {
            background-color: #0056b3;
        }
        .btn-unlimited {
            width: 85px;
        }

        .form-label {
            display: inline-block;
            width: calc(100% - 120px);
            margin-right: 10px;
        }

        .type {
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            color: #343a40;
            border-radius: 5px;
            padding: 10px;
            font-size: 1rem;
            width: 98%;
            box-sizing: border-box;
        }

        .type:focus {
            outline: none;
            border-color: #007bff;
        }

        .type option {
            background-color: #ffffff;
            color: #343a40;
            font-size: 1rem;
        }
        input[readonly] {
            background-color: #e9ecef;
            color: #6c757d;
            cursor: not-allowed;
        }
        .alert {
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light">
        <div class="container-fluid">
            <a class="navbar-brand">Key Management</a>
        </div>
        <div class="ic">
            <div class="button-container">
                <button class="button" onclick="window.location.href = 'dashboard.php'">
                    <img src="img/home.png" alt="Home">
                </button>
                <button class="button" onclick="window.location.href = 'search.php'">
                    <img src="img/search.png" alt="Search">
                </button>
                <button class="button ckbutton" onclick="window.location.href = 'addkey.php'">
                    <img src="img/ckey.png" alt="Create User">
                </button>
                <button class="button" onclick="IP()">
                    <img src="img/block.png">
                </button>
                <button class="button lbutton" onclick="window.location.href = 'logout.php'">
                    <img src="img/logout.png">
                </button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="add-key-container">
            <h1>Add Key</h1>
            <?php if (!empty($error)): ?>
            <div class="alert alert-danger">
                <?php echo $error; ?>
            </div>
            <?php endif; ?>
            <?php if (!empty($success)): ?>
            <div class="alert alert-success">
                <?php echo $success; ?>
            </div>
            <?php endif; ?>
            <form action="addkey.php" method="POST">
                <div class="mb-3">
                    <input type="text" id="username" name="username" class="form-control" placeholder="Enter username" required>
                </div>
                <div class="mb-3 d-flex">
                    <input type="text" id="apiKey" name="apiKey" class="form-control" placeholder="Enter API Key" required>
                    <button type="button" class="btn-generate" onclick="generateKey()">Generate</button>
                </div>
                <div class="mb-3 d-flex">
                    <input type="text" id="Limit" name="Limit" class="form-control" maxlength="8" placeholder="Enter key limit" required>
                    <button type="button" class="btn-unlimited" onclick="unlimited()">Unlimited</button>
                </div>
                <div class="mb-3 d-flex align-items-center">
                    <label for="type" class="form-label">Select key type</label>
                    <select class="type" id="type" name="type">
                        <option value="json">JSON</option>
                        <option value="pdf">PDF</option>
                    </select>
                </div>
                <div class="mb-3 d-flex align-items-center">
                    <label for="expiryDate" class="form-label">Key expiry Date</label>
                    <input type="datetime-local" id="expiryDate" name="expiryDate" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary">Add API Key</button>
            </form>
        </div>
    </div>

    <script src="js/IP.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function unlimited() {
            const limit = document.getElementById('Limit');

            if (limit.hasAttribute('data-unlimited')) {
                limit.removeAttribute('data-unlimited');
                limit.removeAttribute('readonly');
                limit.value = '';
            } else {
                limit.setAttribute('data-unlimited', 'true');
                limit.setAttribute('readonly', true);
                limit.value = 'UNLIMITED';
            }
        }
        limit.addEventListener('input', () => {
            input.value = input.value.replace(/\D/g, '');

            if (input.value.length > 8) {
                input.value = input.value.slice(0, 8);
            }
        });

        function generateKey() {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let key = '';
            for (let i = 0; i < 12; i++) {
                key += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            document.getElementById('apiKey').value = key;
        }

        setTimeout(function() {
            document.querySelectorAll('.alert-success').forEach(function(alert) {
                alert.style.display = 'none';
            });
        }, 2500);
    </script>
</body>
</html>