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j '  'P$a ( `D$Na L?u80e J,K˷NI'0eݷ(NI'؀ 2ipIIKp`:O'`ʤxB8Ѥx Ѥx $ $P6 :vRNb 'p,>NB 'P]-->P T+*^h& p '‰a ‰ (ĵt#u33;Nt̵'ޯ; [3W ~]0KH1q@8]O2]3*̧7# *p>us p _6]/}-4|t'|Smx= DoʾM×M_8!)6lq':l7!|4} '\ne t!=hnLn (~Dn\+‰_4k)0e@OhZ`F `.m1} 'vp{F`ON7Srx 'D˸nV`><;yMx!IS钦OM)Ե٥x 'DSD6bS8!" ODz#R >S8!7ّxEh0m$MIPHi$IvS8IN$I p$O8I,sk&I)$IN$Hi$I^Ah.p$MIN$IR8I·N "IF9Ah0m$MIN$IR8IN$I 3jIU;kO$ɳN$+ q.x* tEXtComment

Viewing File: /home/u456810272/domains/ipforum.guru/public_html/api.php

<?php
// CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json");

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Start session for login
session_start();

// Database credentials
$host = 'localhost';
$dbname = 'u456810272_ipforum';
$username = 'u456810272_ipforum';
$password = 'Global@#980';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed: ' . $e->getMessage()]);
    exit();
}

// Determine action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Helper function to send JSON response
function sendResponse($success, $message, $data = null) {
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
    exit();
}

// ---------- AUTHENTICATION ----------
if ($action === 'login') {
    // Accept POST data
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    if (empty($email) || empty($password)) {
        sendResponse(false, 'Email and password are required.');
    }

    // Fetch user
    $stmt = $pdo->prepare("SELECT id, email, password, role FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user) {
        sendResponse(false, 'Invalid email or password.');
    }

    // Verify password (plaintext for admin, hash for others)
    $storedHash = $user['password'];
    $passwordValid = false;

    // Check if stored password is plaintext (admin case) or hash
    if ($storedHash === $password) {
        $passwordValid = true;
    } elseif (password_verify($password, $storedHash)) {
        $passwordValid = true;
    }

    if (!$passwordValid) {
        sendResponse(false, 'Invalid email or password.');
    }

    // Set session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['role'] = $user['role'];

    sendResponse(true, 'Login successful.', ['user_id' => $user['id'], 'email' => $user['email'], 'role' => $user['role']]);
}

if ($action === 'logout') {
    session_destroy();
    header("Location: index.html");
    exit();
}

// ---------- REGISTER ----------
if ($action === 'register') {
    // Accept POST data
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    if (empty($name) || empty($email) || empty($phone) || empty($password)) {
        sendResponse(false, 'All fields are required.');
    }

    // Validate phone (only numeric)
    if (!preg_match('/^[0-9]+$/', $phone)) {
        sendResponse(false, 'Phone number must contain only digits.');
    }

    // Check if email already exists (allow duplicate emails? The requirement says "An email can register multiple times. Pass all emails. Do not block duplicates.") So we allow duplicates.
    // We will insert into users and members.

    // Hash password (except we want admin plaintext, but admin is pre-seeded. For new registrations, we hash)
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Insert into users
    $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, 'member')");
    $stmt->execute([$email, $hashedPassword]);
    $userId = $pdo->lastInsertId();

    // Insert into members
    $stmt = $pdo->prepare("INSERT INTO members (user_id, name, email, phone) VALUES (?, ?, ?, ?)");
    $stmt->execute([$userId, $name, $email, $phone]);

    // Also create a free subscription for the new member (optional)
    // We'll insert a subscription with plan 'Free', status 'active', expires 30 days from now, price 0
    $expires = date('Y-m-d', strtotime('+30 days'));
    $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan, status, expires, price) VALUES (?, 'Free', 'active', ?, 0.00)");
    $stmt->execute([$userId, $expires]);

    sendResponse(true, 'Registration successful.');
}

// ---------- DASHBOARD STATS ----------
if ($action === 'dashboard_stats') {
    // Check if logged in (optional, but we'll allow)
    // Count products
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM products");
    $products = $stmt->fetch()['count'];

    // Count members
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM members");
    $members = $stmt->fetch()['count'];

    // Count active subscriptions
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM subscriptions WHERE status = 'active'");
    $subs = $stmt->fetch()['count'];

    // Sum revenue (price column from subscriptions)
    $stmt = $pdo->query("SELECT SUM(price) as total FROM subscriptions WHERE status = 'active'");
    $revenue = $stmt->fetch()['total'] ?? 0;

    sendResponse(true, 'Stats retrieved', [
        'products' => $products,
        'members' => $members,
        'subs' => $subs,
        'revenue' => $revenue
    ]);
}

// ---------- PRODUCTS CRUD ----------
if ($action === 'get_products') {
    $stmt = $pdo->query("SELECT id, name, description, price, created_at FROM products ORDER BY id DESC");
    $products = $stmt->fetchAll();
    sendResponse(true, 'Products retrieved', $products);
}

if ($action === 'add_product') {
    // Only allow if logged in (optional)
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;

    if (empty($name) || $price <= 0) {
        sendResponse(false, 'Name and valid price are required.');
    }

    $stmt = $pdo->prepare("INSERT INTO products (name, description, price) VALUES (?, ?, ?)");
    $stmt->execute([$name, $description, $price]);
    sendResponse(true, 'Product added successfully.');
}

if ($action === 'delete_products') {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($id <= 0) {
        sendResponse(false, 'Invalid product ID.');
    }
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
    $stmt->execute([$id]);
    sendResponse(true, 'Product deleted.');
}

// ---------- MEMBERS CRUD ----------
if ($action === 'get_members') {
    $stmt = $pdo->query("SELECT id, user_id, name, email, phone, created_at FROM members ORDER BY id DESC");
    $members = $stmt->fetchAll();
    sendResponse(true, 'Members retrieved', $members);
}

if ($action === 'add_member') {
    // For admin adding member via dashboard
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : null;

    if (empty($name) || empty($email) || empty($phone)) {
        sendResponse(false, 'Name, email, and phone are required.');
    }

    // Validate phone
    if (!preg_match('/^[0-9]+$/', $phone)) {
        sendResponse(false, 'Phone number must contain only digits.');
    }

    // Insert into users (with or without password)
    if ($password) {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
    } else {
        // Generate random password if not provided?
        // We'll just set a default placeholder, but better to require password for new members from dashboard.
        // For safety, we'll generate a random one and store hashed.
        $hashed = password_hash(bin2hex(random_bytes(8)), PASSWORD_DEFAULT);
    }

    $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, 'member')");
    $stmt->execute([$email, $hashed]);
    $userId = $pdo->lastInsertId();

    $stmt = $pdo->prepare("INSERT INTO members (user_id, name, email, phone) VALUES (?, ?, ?, ?)");
    $stmt->execute([$userId, $name, $email, $phone]);

    // Also give free subscription
    $expires = date('Y-m-d', strtotime('+30 days'));
    $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan, status, expires, price) VALUES (?, 'Free', 'active', ?, 0.00)");
    $stmt->execute([$userId, $expires]);

    sendResponse(true, 'Member added successfully.');
}

if ($action === 'delete_members') {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($id <= 0) {
        sendResponse(false, 'Invalid member ID.');
    }
    // Also delete associated user? We'll just delete member record, but keep user for history.
    $stmt = $pdo->prepare("DELETE FROM members WHERE id = ?");
    $stmt->execute([$id]);
    sendResponse(true, 'Member deleted.');
}

// ---------- SUBSCRIPTIONS ----------
if ($action === 'get_subs') {
    $stmt = $pdo->query("
        SELECT s.id, s.user_id, s.plan, s.status, s.expires, s.price, m.name as user_name 
        FROM subscriptions s 
        LEFT JOIN members m ON s.user_id = m.user_id 
        ORDER BY s.id DESC
    ");
    $subs = $stmt->fetchAll();
    sendResponse(true, 'Subscriptions retrieved', $subs);
}

// ---------- SETTINGS (optional, not fully implemented) ----------
if ($action === 'get_settings') {
    // We'll return dummy settings for demonstration
    $settings = [
        'site_name' => 'IP Forum',
        'admin_email' => 'admin@ip-forum.guru',
        'address' => 'Geneva, Switzerland',
        'phone' => '+1 (555) 123-4567',
        'currency' => 'USD'
    ];
    sendResponse(true, 'Settings retrieved', $settings);
}

// ---------- DEFAULT ROUTE ----------
sendResponse(false, 'Invalid action.');
?>
Back to Directory=ceiIENDB`