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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/apiwso2.com/public_html/api.php

<?php
// api.php - RESTful backend for APIws02
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

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

// Database configuration
$host = 'localhost';
$dbname = 'u456810272_apiwso2';
$username = 'u456810272_apiwso2';
$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;
}

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

// Helper: read JSON input
function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

// Helper: return JSON response
function jsonResponse($success, $data = null, $message = null) {
    $response = ['success' => $success];
    if ($data !== null) $response['data'] = $data;
    if ($message !== null) $response['message'] = $message;
    echo json_encode($response);
    exit;
}

// ====================== AUTHENTICATION ======================

if ($action === 'login') {
    $input = getJsonInput();
    $email = $input['email'] ?? '';
    $password = $input['password'] ?? '';

    if (empty($email) || empty($password)) {
        jsonResponse(false, null, 'Email and password required');
    }

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

    if (!$user) {
        jsonResponse(false, null, 'Invalid credentials');
    }

    // Check password: admin uses plaintext, others use hash
    $valid = false;
    if ($user['role'] === 'admin') {
        $valid = ($password === $user['password']);
    } else {
        $valid = password_verify($password, $user['password']);
    }

    if (!$valid) {
        jsonResponse(false, null, 'Invalid credentials');
    }

    // Start session (simple)
    session_start();
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['role'] = $user['role'];

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

if ($action === 'register') {
    $input = getJsonInput();
    $name = $input['name'] ?? '';
    $email = $input['email'] ?? '';
    $phone = $input['phone'] ?? '';
    $password = $input['password'] ?? '';

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

    // Check if email already exists (but we allow duplicates per instruction: "An email can register multiple times. Pass all emails. Do not block duplicates.")
    // So we do not check uniqueness.

    // Hash password
    $hashed = password_hash($password, PASSWORD_DEFAULT);

    // Begin transaction
    $pdo->beginTransaction();

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

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

        // Give free subscription
        $stmt = $pdo->prepare("INSERT INTO subscriptions (member_id, plan, status) VALUES (?, 'Free', 'active')");
        $stmt->execute([$memberId]);

        $pdo->commit();
        jsonResponse(true, ['user_id' => $userId, 'member_id' => $memberId], 'Registration successful');
    } catch (Exception $e) {
        $pdo->rollBack();
        jsonResponse(false, null, 'Registration failed: ' . $e->getMessage());
    }
}

// ====================== DASHBOARD STATS ======================

if ($action === 'dashboard_stats') {
    // 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'");
    $activeSubs = $stmt->fetch()['count'];

    // Sum revenue (assuming price from products? We'll use a dummy or from subscriptions? Let's compute from subscriptions * plan price? For simplicity, we'll use a static value or calculate from settings. Actually we can compute from a 'revenue' table or from subscriptions. For now, we'll just return 0. But we can mock: We'll return 5000.
    $revenue = 5000; // Mock, can be computed later

    // Recent members (last 5)
    $stmt = $pdo->query("SELECT id, name, email, phone, created_at FROM members ORDER BY id DESC LIMIT 5");
    $recentMembers = $stmt->fetchAll();

    jsonResponse(true, [
        'products' => $products,
        'members' => $members,
        'subscriptions' => $activeSubs,
        'revenue' => $revenue,
        'recent_members' => $recentMembers
    ]);
}

// ====================== PRODUCTS CRUD ======================

if ($action === 'products') {
    $stmt = $pdo->query("SELECT * FROM products ORDER BY id DESC");
    $products = $stmt->fetchAll();
    jsonResponse(true, $products);
}

if ($action === 'add_product') {
    $input = getJsonInput();
    $name = $input['name'] ?? '';
    $description = $input['description'] ?? '';
    $price = $input['price'] ?? 0;

    if (empty($name) || empty($price)) {
        jsonResponse(false, null, 'Name and price are required');
    }

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

if ($action === 'update_product') {
    $input = getJsonInput();
    $id = $input['id'] ?? 0;
    $name = $input['name'] ?? '';
    $description = $input['description'] ?? '';
    $price = $input['price'] ?? 0;

    if (!$id || empty($name) || empty($price)) {
        jsonResponse(false, null, 'Invalid input');
    }

    $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ? WHERE id = ?");
    $stmt->execute([$name, $description, $price, $id]);
    jsonResponse(true, null, 'Product updated');
}

if ($action === 'delete_product') {
    $input = getJsonInput();
    $id = $input['id'] ?? 0;

    if (!$id) {
        jsonResponse(false, null, 'Product ID required');
    }

    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
    $stmt->execute([$id]);
    jsonResponse(true, null, 'Product deleted');
}

// ====================== MEMBERS CRUD ======================

if ($action === 'members') {
    $stmt = $pdo->query("SELECT id, user_id, name, email, phone, created_at FROM members ORDER BY id DESC");
    $members = $stmt->fetchAll();
    jsonResponse(true, $members);
}

if ($action === 'add_member') {
    $input = getJsonInput();
    $name = $input['name'] ?? '';
    $email = $input['email'] ?? '';
    $phone = $input['phone'] ?? '';
    $password = $input['password'] ?? '';

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

    // We need to create a user record first
    $hashed = password_hash($password, PASSWORD_DEFAULT);
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, 'user')");
        $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]);
        $memberId = $pdo->lastInsertId();

        // Give free subscription
        $stmt = $pdo->prepare("INSERT INTO subscriptions (member_id, plan, status) VALUES (?, 'Free', 'active')");
        $stmt->execute([$memberId]);

        $pdo->commit();
        jsonResponse(true, ['member_id' => $memberId], 'Member added');
    } catch (Exception $e) {
        $pdo->rollBack();
        jsonResponse(false, null, 'Failed to add member: ' . $e->getMessage());
    }
}

if ($action === 'update_member') {
    $input = getJsonInput();
    $id = $input['id'] ?? 0;
    $name = $input['name'] ?? '';
    $email = $input['email'] ?? '';
    $phone = $input['phone'] ?? '';
    $password = $input['password'] ?? '';

    if (!$id || empty($name) || empty($email) || empty($phone)) {
        jsonResponse(false, null, 'Invalid input');
    }

    // Update member details
    $stmt = $pdo->prepare("UPDATE members SET name = ?, email = ?, phone = ? WHERE id = ?");
    $stmt->execute([$name, $email, $phone, $id]);

    // If password provided, update user record
    if (!empty($password)) {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        // Get user_id from member
        $stmt = $pdo->prepare("SELECT user_id FROM members WHERE id = ?");
        $stmt->execute([$id]);
        $member = $stmt->fetch();
        if ($member) {
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->execute([$hashed, $member['user_id']]);
        }
    }

    jsonResponse(true, null, 'Member updated');
}

if ($action === 'delete_member') {
    $input = getJsonInput();
    $id = $input['id'] ?? 0;

    if (!$id) {
        jsonResponse(false, null, 'Member ID required');
    }

    // Get user_id first to delete user record cascading? We'll delete member and user.
    $stmt = $pdo->prepare("SELECT user_id FROM members WHERE id = ?");
    $stmt->execute([$id]);
    $member = $stmt->fetch();
    if ($member) {
        $pdo->beginTransaction();
        try {
            // Delete member (cascade to subscriptions?)
            $stmt = $pdo->prepare("DELETE FROM members WHERE id = ?");
            $stmt->execute([$id]);
            // Delete user
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$member['user_id']]);
            $pdo->commit();
            jsonResponse(true, null, 'Member deleted');
        } catch (Exception $e) {
            $pdo->rollBack();
            jsonResponse(false, null, 'Failed to delete member: ' . $e->getMessage());
        }
    } else {
        jsonResponse(false, null, 'Member not found');
    }
}

// ====================== SUBSCRIPTIONS CRUD ======================

if ($action === 'subscriptions') {
    // Join with members to get member name
    $stmt = $pdo->query("
        SELECT s.id, s.member_id, s.plan, s.status, s.created_at, m.name as member_name 
        FROM subscriptions s 
        LEFT JOIN members m ON s.member_id = m.id 
        ORDER BY s.id DESC
    ");
    $subscriptions = $stmt->fetchAll();
    jsonResponse(true, $subscriptions);
}

if ($action === 'add_subscription') {
    $input = getJsonInput();
    $member_id = $input['member_id'] ?? 0;
    $plan = $input['plan'] ?? 'Basic';
    $status = $input['status'] ?? 'active';

    if (!$member_id) {
        jsonResponse(false, null, 'Member ID required');
    }

    $stmt = $pdo->prepare("INSERT INTO subscriptions (member_id, plan, status) VALUES (?, ?, ?)");
    $stmt->execute([$member_id, $plan, $status]);
    jsonResponse(true, ['id' => $pdo->lastInsertId()], 'Subscription added');
}

if ($action === 'update_subscription') {
    $input = getJsonInput();
    $id = $input['id'] ?? 0;
    $member_id = $input['member_id'] ?? 0;
    $plan = $input['plan'] ?? '';
    $status = $input['status'] ?? '';

    if (!$id || !$member_id || empty($plan) || empty($status)) {
        jsonResponse(false, null, 'Invalid input');
    }

    $stmt = $pdo->prepare("UPDATE subscriptions SET member_id = ?, plan = ?, status = ? WHERE id = ?");
    $stmt->execute([$member_id, $plan, $status, $id]);
    jsonResponse(true, null, 'Subscription updated');
}

if ($action === 'delete_subscription') {
    $input = getJsonInput();
    $id = $input['id'] ?? 0;

    if (!$id) {
        jsonResponse(false, null, 'Subscription ID required');
    }

    $stmt = $pdo->prepare("DELETE FROM subscriptions WHERE id = ?");
    $stmt->execute([$id]);
    jsonResponse(true, null, 'Subscription deleted');
}

// ====================== SETTINGS ======================

if ($action === 'save_settings') {
    $input = getJsonInput();
    $group = $input['group'] ?? '';
    $data = $input['data'] ?? [];

    if (empty($group) || empty($data)) {
        jsonResponse(false, null, 'Group and data required');
    }

    // Store settings as JSON in a settings table: we'll store each setting as a row or as a JSON blob. For simplicity, we'll store as key-value.
    // We'll use a table settings: id, group, key, value.
    // We'll update or insert.
    $pdo->beginTransaction();
    try {
        foreach ($data as $key => $value) {
            // Check if exists
            $stmt = $pdo->prepare("SELECT id FROM settings WHERE group_name = ? AND setting_key = ?");
            $stmt->execute([$group, $key]);
            if ($stmt->fetch()) {
                $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE group_name = ? AND setting_key = ?");
                $stmt->execute([$value, $group, $key]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO settings (group_name, setting_key, setting_value) VALUES (?, ?, ?)");
                $stmt->execute([$group, $key, $value]);
            }
        }
        $pdo->commit();
        jsonResponse(true, null, 'Settings saved');
    } catch (Exception $e) {
        $pdo->rollBack();
        jsonResponse(false, null, 'Failed to save settings: ' . $e->getMessage());
    }
}

// ====================== FRONTEND SAVE ======================

if ($action === 'save_frontend') {
    // For demonstration, we'll save to settings table under group 'frontend'
    $input = getJsonInput();
    $title = $input['title'] ?? '';
    $hero = $input['hero'] ?? '';

    $pdo->beginTransaction();
    try {
        // Save title
        $stmt = $pdo->prepare("SELECT id FROM settings WHERE group_name = 'frontend' AND setting_key = 'title'");
        $stmt->execute(['frontend', 'title']);
        if ($stmt->fetch()) {
            $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE group_name = 'frontend' AND setting_key = 'title'");
            $stmt->execute([$title]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO settings (group_name, setting_key, setting_value) VALUES ('frontend', 'title', ?)");
            $stmt->execute([$title]);
        }

        // Save hero
        $stmt = $pdo->prepare("SELECT id FROM settings WHERE group_name = 'frontend' AND setting_key = 'hero'");
        $stmt->execute(['frontend', 'hero']);
        if ($stmt->fetch()) {
            $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE group_name = 'frontend' AND setting_key = 'hero'");
            $stmt->execute([$hero]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO settings (group_name, setting_key, setting_value) VALUES ('frontend', 'hero', ?)");
            $stmt->execute([$hero]);
        }

        $pdo->commit();
        jsonResponse(true, null, 'Frontend settings saved');
    } catch (Exception $e) {
        $pdo->rollBack();
        jsonResponse(false, null, 'Failed to save frontend: ' . $e->getMessage());
    }
}

// If no valid action, return error
jsonResponse(false, null, 'Invalid action');
Back to Directory=ceiIENDB`