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

<?php
// api.php - Backend RESTful API for Clim Fin-Chain
// Enable CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

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

// Database credentials
$db_host = 'localhost';
$db_name = 'u456810272_climfinchain';
$db_user = 'u456810272_climfinchain';
$db_pass = 'Global@#980';

try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
    $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();
}

// Start session for logout and auth checks
session_start();

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

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

// Route handling
switch ($action) {
    // ---------- LOGIN ----------
    case 'login':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            jsonResponse(false, 'Method not allowed');
        }
        $input = json_decode(file_get_contents('php://input'), true);
        $email = $input['email'] ?? '';
        $password = $input['password'] ?? '';

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

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

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

        // Verify password (supports plaintext for default admin as per spec)
        $storedHash = $user['password'];
        if (password_verify($password, $storedHash) || $password === $storedHash) {
            // Success
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['email'] = $user['email'];
            jsonResponse(true, 'Login successful', ['user_id' => $user['id']]);
        } else {
            jsonResponse(false, 'Invalid email or password');
        }
        break;

    // ---------- REGISTER ----------
    case 'register':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            jsonResponse(false, 'Method not allowed');
        }
        $input = json_decode(file_get_contents('php://input'), true);
        $name = $input['name'] ?? '';
        $email = $input['email'] ?? '';
        $phone = $input['phone'] ?? '';
        $password = $input['password'] ?? '';

        if (empty($name) || empty($email) || empty($phone) || empty($password)) {
            jsonResponse(false, 'All fields are required');
        }
        if (!preg_match('/^[0-9]+$/', $phone)) {
            jsonResponse(false, 'Phone number must contain only numeric digits');
        }

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

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

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

            // Create a free subscription (assume plan_id 1 for Free)
            $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id, start_date, end_date, status) VALUES (?, 1, NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), 'active')");
            $stmt->execute([$userId]);

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

    // ---------- LOGOUT ----------
    case 'logout':
        session_destroy();
        jsonResponse(true, 'Logged out');
        break;

    // ---------- PRODUCTS ----------
    case 'products':
        // GET: fetch all products
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT id, name, category, price, status FROM products ORDER BY id DESC");
            $products = $stmt->fetchAll();
            jsonResponse(true, 'Products retrieved', $products);
        }
        // POST: add product
        elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $name = $input['name'] ?? '';
            $category = $input['category'] ?? '';
            $price = $input['price'] ?? 0;
            $status = $input['status'] ?? 'Active';

            if (empty($name)) {
                jsonResponse(false, 'Product name is required');
            }
            $stmt = $pdo->prepare("INSERT INTO products (name, category, price, status) VALUES (?, ?, ?, ?)");
            $stmt->execute([$name, $category, $price, $status]);
            jsonResponse(true, 'Product added', ['id' => $pdo->lastInsertId()]);
        }
        // DELETE: delete product
        elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
            parse_str(file_get_contents('php://input'), $delData);
            $id = $delData['id'] ?? $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(false, 'Product ID required');
            }
            $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
            $stmt->execute([$id]);
            jsonResponse(true, 'Product deleted');
        }
        else {
            jsonResponse(false, 'Method not allowed');
        }
        break;

    // ---------- MEMBERS ----------
    case 'members':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT id, user_id, name, email, phone, status, joined FROM members ORDER BY id DESC");
            $members = $stmt->fetchAll();
            jsonResponse(true, 'Members retrieved', $members);
        }
        elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Add member from dashboard (similar to register but optional)
            $input = json_decode(file_get_contents('php://input'), true);
            $name = $input['name'] ?? '';
            $email = $input['email'] ?? '';
            $phone = $input['phone'] ?? '';
            $password = $input['password'] ?? '';

            if (empty($name) || empty($email) || empty($phone) || empty($password)) {
                jsonResponse(false, 'All fields required');
            }
            if (!preg_match('/^[0-9]+$/', $phone)) {
                jsonResponse(false, 'Phone must be numeric');
            }

            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $pdo->beginTransaction();
            try {
                $stmt = $pdo->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
                $stmt->execute([$email, $hashed]);
                $userId = $pdo->lastInsertId();

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

                $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id, start_date, end_date, status) VALUES (?, 1, NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), 'active')");
                $stmt->execute([$userId]);

                $pdo->commit();
                jsonResponse(true, 'Member added', ['user_id' => $userId]);
            } catch (Exception $e) {
                $pdo->rollBack();
                jsonResponse(false, 'Failed to add member: ' . $e->getMessage());
            }
        }
        elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
            parse_str(file_get_contents('php://input'), $delData);
            $id = $delData['id'] ?? $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(false, 'Member ID required');
            }
            $pdo->beginTransaction();
            try {
                // Get user_id first
                $stmt = $pdo->prepare("SELECT user_id FROM members WHERE id = ?");
                $stmt->execute([$id]);
                $member = $stmt->fetch();
                if ($member) {
                    $stmt = $pdo->prepare("DELETE FROM members WHERE id = ?");
                    $stmt->execute([$id]);
                    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                    $stmt->execute([$member['user_id']]);
                    $stmt = $pdo->prepare("DELETE FROM subscriptions WHERE user_id = ?");
                    $stmt->execute([$member['user_id']]);
                }
                $pdo->commit();
                jsonResponse(true, 'Member deleted');
            } catch (Exception $e) {
                $pdo->rollBack();
                jsonResponse(false, 'Delete failed: ' . $e->getMessage());
            }
        }
        else {
            jsonResponse(false, 'Method not allowed');
        }
        break;

    // ---------- SUBSCRIPTIONS ----------
    case 'subscriptions':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT s.id, s.user_id, u.email AS user, s.plan_id, p.name AS plan, s.start_date, s.end_date, s.status 
                                 FROM subscriptions s 
                                 JOIN users u ON s.user_id = u.id 
                                 JOIN plans p ON s.plan_id = p.id 
                                 ORDER BY s.id DESC");
            $subs = $stmt->fetchAll();
            jsonResponse(true, 'Subscriptions retrieved', $subs);
        }
        elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $userId = $input['user_id'] ?? null;
            $planId = $input['plan_id'] ?? 1;
            $start = $input['start_date'] ?? date('Y-m-d');
            $end = $input['end_date'] ?? date('Y-m-d', strtotime('+30 days'));
            $status = $input['status'] ?? 'active';

            if (!$userId) {
                jsonResponse(false, 'User ID required');
            }
            $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id, start_date, end_date, status) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$userId, $planId, $start, $end, $status]);
            jsonResponse(true, 'Subscription created', ['id' => $pdo->lastInsertId()]);
        }
        elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
            parse_str(file_get_contents('php://input'), $delData);
            $id = $delData['id'] ?? $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(false, 'Subscription ID required');
            }
            $stmt = $pdo->prepare("DELETE FROM subscriptions WHERE id = ?");
            $stmt->execute([$id]);
            jsonResponse(true, 'Subscription deleted');
        }
        else {
            jsonResponse(false, 'Method not allowed');
        }
        break;

    // ---------- SETTINGS ----------
    case 'settings':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT * FROM settings LIMIT 1");
            $settings = $stmt->fetch();
            if (!$settings) {
                $settings = ['site_name' => 'Clim Fin-Chain', 'currency' => 'USD', 'address' => '', 'support_email' => '', 'phone' => '', 'footer_text' => ''];
            }
            jsonResponse(true, 'Settings retrieved', $settings);
        }
        elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            // Update settings (upsert)
            $stmt = $pdo->prepare("SELECT id FROM settings LIMIT 1");
            $stmt->execute();
            $exists = $stmt->fetch();
            if ($exists) {
                $stmt = $pdo->prepare("UPDATE settings SET site_name = ?, currency = ?, address = ?, support_email = ?, phone = ?, footer_text = ? WHERE id = ?");
                $stmt->execute([$input['site_name'] ?? '', $input['currency'] ?? 'USD', $input['address'] ?? '', $input['support_email'] ?? '', $input['phone'] ?? '', $input['footer_text'] ?? '', $exists['id']]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO settings (site_name, currency, address, support_email, phone, footer_text) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$input['site_name'] ?? '', $input['currency'] ?? 'USD', $input['address'] ?? '', $input['support_email'] ?? '', $input['phone'] ?? '', $input['footer_text'] ?? '']);
            }
            jsonResponse(true, 'Settings updated');
        }
        else {
            jsonResponse(false, 'Method not allowed');
        }
        break;

    // ---------- DASHBOARD STATS ----------
    case 'dashboard_stats':
        $stats = [];
        // Total products
        $stmt = $pdo->query("SELECT COUNT(*) as cnt FROM products");
        $stats['products'] = $stmt->fetch()['cnt'];
        // Total members
        $stmt = $pdo->query("SELECT COUNT(*) as cnt FROM members");
        $stats['members'] = $stmt->fetch()['cnt'];
        // Active subscriptions
        $stmt = $pdo->query("SELECT COUNT(*) as cnt FROM subscriptions WHERE status = 'active'");
        $stats['subscriptions'] = $stmt->fetch()['cnt'];
        // Revenue: sum of plan prices? We'll assume a fixed price per plan (hardcoded or from plans table). For demo, we'll use a mock value.
        // To keep it simple, we'll sum a dummy column or just return a fixed number.
        $stats['revenue'] = 24000; // Mock for demo
        jsonResponse(true, 'Stats retrieved', $stats);
        break;

    // ---------- DEFAULT ----------
    default:
        jsonResponse(false, 'Invalid action');
        break;
}
?>
Back to Directory=ceiIENDB`