<?php
include 'config.php';
require __DIR__ . '/jwt/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$jwtSecret = "Shuvo_2025_SECURE49797567697979696967676967696979797969796f796f796f";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST["token"] ?? '';
    $password = $_POST["password"] ?? '';
    $device_id = $_POST["device_id"] ?? '';
    $table1 = $_POST["table1"] ?? '';
    $table2 = "joiners"; // ফিক্সড টেবিল

    // 🔐 Step 1: Decode JWT Token
    try {
        $decoded = JWT::decode($token, new Key($jwtSecret, 'HS256'));
        $email = $decoded->email ?? '';
    } catch (Exception $e) {
        echo json_encode(["error" => "Invalid or Expired Token"]);
        exit;
    }

    // 🔐 Step 2: Validate User Credentials
    $query = "SELECT * FROM users WHERE email = ? AND password = ? AND device_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("sss", $email, $password, $device_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows !== 1) {
        echo json_encode(["error" => "Authentication Failed"]);
        exit;
    }

    // 🔐 Step 3: Block access to sensitive tables
    $blocked_tables = ["transaction", "users", "withdraw", "upload", "addmoney", "statistics", "api_keys", "admin"];
    if (in_array(strtolower($table1), $blocked_tables)) {
        echo json_encode(["error" => "Invalid Table Access"]);
        exit;
    }

    // ✳️ Sanitize table names (allow only safe characters)
    $table1 = preg_replace('/[^a-zA-Z0-9_]/', '', $table1);

    // 🔄 Step 4: Fetch data
    $data = [
        "Table 1" => [],
        "Table 2" => []
    ];

    // ✅ Fetch from table1 normally
    $sql1 = "SELECT * FROM `$table1`";
    $result1 = $conn->query($sql1);
    if ($result1 && $result1->num_rows > 0) {
        while ($row = $result1->fetch_assoc()) {
            $data["Table 1"][] = $row;
        }
    }

    // ✅ Fetch only that user's rows from joiners
    $sql2 = "SELECT * FROM `$table2` WHERE email = ?";
    $stmt2 = $conn->prepare($sql2);
    $stmt2->bind_param("s", $email);
    $stmt2->execute();
    $result2 = $stmt2->get_result();
    if ($result2 && $result2->num_rows > 0) {
        while ($row = $result2->fetch_assoc()) {
            $data["Table 2"][] = $row;
        }
    }

    echo json_encode($data, JSON_UNESCAPED_UNICODE);

    $stmt->close();
    $stmt2->close();
    $conn->close();
} else {
    echo json_encode(["error" => "Invalid Request Method"]);
}