<?php
require_once __DIR__ . "/../config.php";

/*
-----------------------------------------------
 FX-HUNTER API AUTH — FINAL MATCHED TO YOUR DB
-----------------------------------------------
 Matches real table fxh_users:
   id
   email
   password_hash
   status
-----------------------------------------------
*/

function API_AUTH()
{
    global $conn;

    // ===================================================
    // 1️⃣ SESSION LOGIN (Dashboard Actions)
    // ===================================================
    if (isset($_SESSION['user_id'])) {

        $uid = intval($_SESSION['user_id']);

        // Your REAL table + REAL columns
        $stmt = $conn->prepare("
            SELECT id, email, status
            FROM fxh_users
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->bind_param("i", $uid);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows == 0) {
            http_response_code(403);
            echo json_encode(["error" => "INVALID_SESSION"]);
            exit;
        }

        return $res->fetch_assoc();
    }

    // ===================================================
    // 2️⃣ TOKEN AUTH DISABLED (not used in your system)
    // ===================================================
    // If in future you add an api_token column, re-enable this.
    http_response_code(403);
    echo json_encode(["error" => "AUTH_REQUIRED"]);
    exit;
}

function API_AUTH_DESKTOP()
{
    global $conn;

    $headers = getallheaders();
    if (!isset($headers['Authorization'])) {
        http_response_code(401);
        echo json_encode(["error" => "NO_AUTH_HEADER"]);
        exit;
    }

    $token = trim(str_replace("Bearer", "", $headers['Authorization']));

    // 🔐 Validate token against LOGIN TOKENS
    $stmt = $conn->prepare("
        SELECT id, email, status
        FROM fxh_desktop_tokens
        WHERE token = ?
        AND status = 'active'
        LIMIT 1
    ");

    $stmt->bind_param("s", $token);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 0) {
        http_response_code(401);
        echo json_encode(["error" => "INVALID_TOKEN"]);
        exit;
    }

    return $res->fetch_assoc();
}

