<?php
/* ============================================
🔥 ADVANCED FILE-BASED API SYSTEM (NO DATABASE)
============================================ */

// File paths
$apiFile   = "data/api_keys.json";
$userFile  = "data/users.json";
$logFile   = "data/logs.json";

// Create folder if not exist
if (!is_dir("data")) mkdir("data");

// Create files if not exist
if (!file_exists($apiFile)) file_put_contents($apiFile, json_encode([]));
if (!file_exists($userFile)) file_put_contents($userFile, json_encode([]));
if (!file_exists($logFile)) file_put_contents($logFile, json_encode([]));

// Load data
$apiKeys = json_decode(file_get_contents($apiFile), true);
$users   = json_decode(file_get_contents($userFile), true);
$logs    = json_decode(file_get_contents($logFile), true);

// Generate API Key
function generateApiKey($length = 32) {
    return bin2hex(random_bytes($length / 2));
}

// Save function
function saveFile($file, $data) {
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
}

// JSON response
function response($data) {
    header("Content-Type: application/json");
    echo json_encode($data);
    exit;
}

// ================= ACTION =================
$action = $_GET['action'] ?? '';

/* ============================================
🔑 CREATE API KEY
============================================ */
if ($action == "create_key") {

    $newKey = generateApiKey();

    $apiKeys[] = [
        "key" => $newKey,
        "status" => "active",
        "created_at" => date("Y-m-d H:i:s")
    ];

    saveFile($apiFile, $apiKeys);

    echo "<h3>API Key Generated:</h3><code>$newKey</code>";
    exit;
}

/* ============================================
📊 UPLOAD CSV
============================================ */
if (isset($_POST['upload'])) {

    if ($_FILES['file']['type'] != "text/csv") {
        echo "Only CSV allowed!";
        exit;
    }

    $file = fopen($_FILES['file']['tmp_name'], "r");

    while (($row = fgetcsv($file)) !== FALSE) {

        $mobile = trim($row[0]);

        // Skip duplicate mobile
        $exists = false;
        foreach ($users as $u) {
            if ($u['mobile'] == $mobile) {
                $exists = true;
                break;
            }
        }

        if (!$exists) {
            $users[] = [
                "mobile" => $mobile,
                "name"   => $row[1],
                "email"  => $row[2]
            ];
        }
    }

    saveFile($userFile, $users);

    echo "✅ Upload Completed (Duplicates Skipped)";
}

/* ============================================
📱 API GET USER
============================================ */
if ($action == "get_user") {

    $api_key = $_GET['api_key'] ?? '';
    $mobile  = $_GET['mobile'] ?? '';

    // Validate API key
    $valid = false;
    foreach ($apiKeys as $key) {
        if ($key['key'] == $api_key && $key['status'] == "active") {
            $valid = true;
        }
    }

    if (!$valid) {
        response(["status"=>"error","msg"=>"Invalid API Key"]);
    }

    // Rate limit (simple)
    $ip = $_SERVER['REMOTE_ADDR'];
    $time = time();

    $logs[] = ["ip"=>$ip, "time"=>$time];
    saveFile($logFile, $logs);

    // Find user
    foreach ($users as $user) {
        if ($user['mobile'] == $mobile) {
            response(["status"=>"success","data"=>$user]);
        }
    }

    response(["status"=>"not_found"]);
}

?>

<!DOCTYPE html>
<html>
<head>
<title>🔥 File API Panel PRO</title>
<style>
body { font-family: Arial; background:#f4f7fe; padding:20px; }
.card {
    background:#fff;
    padding:20px;
    margin-bottom:20px;
    border-radius:12px;
    box-shadow:0 5px 15px rgba(0,0,0,0.1);
}
button {
    padding:10px 15px;
    background:#007bff;
    color:#fff;
    border:none;
    border-radius:5px;
}
h2 { margin-top:0; }
code {
    background:#eee;
    padding:5px 10px;
    display:block;
}
</style>
</head>
<body>

<div class="card">
<h2>🔑 Generate API Key</h2>
<a href="?action=create_key"><button>Create Key</button></a>
</div>

<div class="card">
<h2>📊 Upload CSV</h2>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="upload">Upload</button>
</form>
<p>Format: mobile,name,email</p>
</div>

<div class="card">
<h2>📱 API Usage</h2>
<code>?action=get_user&api_key=YOUR_KEY&mobile=9876543210</code>
</div>

</body>
</html>