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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/brokerjob.org/public_html/api.php

<?php
// api.php - BrokerJob Backend RESTful API
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 credentials (as provided)
$host = 'localhost';
$dbname = 'u456810272_brokerjobb';
$username = 'u456810272_brokerjobb';
$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(['status' => 'error', 'message' => 'Database connection failed: ' . $e->getMessage()]);
    exit();
}

// Start session for logout and session checks
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Helper function to send JSON response
function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit();
}

// Get action from request
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

if (empty($action)) {
    sendResponse(['status' => 'error', 'message' => 'Action parameter required']);
}

// --- ACTION HANDLERS ---

// ========== LOGIN ==========
if ($action === 'login') {
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    if (empty($email) || empty($password)) {
        sendResponse(['status' => 'error', 'message' => 'Email and password required']);
    }

    // Fetch user from users table
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user) {
        sendResponse(['status' => 'error', 'message' => 'Invalid credentials']);
    }

    // Verify password: for admin (email admin@brokerjob.org) we use plaintext as per instructions, for others use password_verify
    $isAdmin = ($email === 'admin@brokerjob.org');
    if ($isAdmin) {
        $valid = ($password === $user['password']); // plaintext stored
    } else {
        $valid = password_verify($password, $user['password']);
    }

    if (!$valid) {
        sendResponse(['status' => 'error', 'message' => 'Invalid credentials']);
    }

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

    // Also fetch member info
    $stmtMember = $pdo->prepare("SELECT * FROM members WHERE user_id = ?");
    $stmtMember->execute([$user['id']]);
    $member = $stmtMember->fetch();

    sendResponse(['status' => 'success', 'message' => 'Login successful', 'data' => ['user' => $user, 'member' => $member]]);
}

// ========== REGISTER ==========
if ($action === 'register') {
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $password = $_POST['password'] ?? '';
    $accountType = $_POST['account_type'] ?? 'jobseeker';

    if (empty($name) || empty($email) || empty($phone) || empty($password)) {
        sendResponse(['status' => 'error', 'message' => 'All fields are required']);
    }

    // Validate phone: only digits
    if (!preg_match('/^[0-9]+$/', $phone)) {
        sendResponse(['status' => 'error', 'message' => 'Phone must contain only digits']);
    }

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

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

    try {
        // Insert into users (email can repeat, as per instructions)
        $stmtUser = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, ?)");
        $stmtUser->execute([$email, $hashedPassword, 'user']);
        $userId = $pdo->lastInsertId();

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

        // Insert free subscription
        $stmtSub = $pdo->prepare("INSERT INTO subscriptions (user_id, plan, status) VALUES (?, 'Free', 'active')");
        $stmtSub->execute([$userId]);

        $pdo->commit();

        sendResponse(['status' => 'success', 'message' => 'Registration successful']);
    } catch (Exception $e) {
        $pdo->rollBack();
        sendResponse(['status' => 'error', 'message' => 'Registration failed: ' . $e->getMessage()]);
    }
}

// ========== LOGOUT ==========
if ($action === 'logout') {
    session_destroy();
    sendResponse(['status' => 'success', 'message' => 'Logged out']);
}

// ========== DASHBOARD STATS ==========
if ($action === 'dashboard_stats') {
    // Count products
    $stmtProd = $pdo->query("SELECT COUNT(*) as count FROM products");
    $products = $stmtProd->fetch()['count'];

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

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

    // Revenue: sum of product prices (mock)
    $stmtRev = $pdo->query("SELECT SUM(price) as revenue FROM products");
    $revenue = $stmtRev->fetch()['revenue'] ?? 0;

    // Revenue trend (mock data for last 6 months)
    $revenueTrend = [1200, 1500, 1800, 2200, 2700, 3200]; // could be computed from orders if we had

    // Subscription breakdown
    $stmtBreak = $pdo->query("SELECT plan, COUNT(*) as count FROM subscriptions GROUP BY plan");
    $breakdown = [];
    while ($row = $stmtBreak->fetch()) {
        $breakdown[$row['plan']] = $row['count'];
    }
    // Ensure all three plans exist
    $subBreakdown = [
        'Free' => $breakdown['Free'] ?? 0,
        'Basic' => $breakdown['Basic'] ?? 0,
        'Premium' => $breakdown['Premium'] ?? 0
    ];

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

    sendResponse([
        'status' => 'success',
        'data' => [
            'products' => $products,
            'members' => $members,
            'subscriptions' => $subscriptions,
            'revenue' => $revenue,
            'revenue_trend' => $revenueTrend,
            'sub_breakdown' => $subBreakdown,
            'recent_members' => $recentMembers
        ]
    ]);
}

// ========== PRODUCTS CRUD ==========
if ($action === 'products') {
    // GET list of products
    $stmt = $pdo->query("SELECT * FROM products ORDER BY id DESC");
    $data = $stmt->fetchAll();
    sendResponse(['status' => 'success', 'data' => $data]);
}

if ($action === 'save_product') {
    $id = $_POST['id'] ?? null;
    $name = $_POST['name'] ?? '';
    $price = $_POST['price'] ?? 0;
    $status = $_POST['status'] ?? 'active';

    if (empty($name)) {
        sendResponse(['status' => 'error', 'message' => 'Product name required']);
    }

    if ($id) {
        // Update
        $stmt = $pdo->prepare("UPDATE products SET name = ?, price = ?, status = ? WHERE id = ?");
        $stmt->execute([$name, $price, $status, $id]);
    } else {
        // Insert
        $stmt = $pdo->prepare("INSERT INTO products (name, price, status) VALUES (?, ?, ?)");
        $stmt->execute([$name, $price, $status]);
    }
    sendResponse(['status' => 'success', 'message' => 'Product saved']);
}

if ($action === 'delete_product') {
    $id = $_GET['id'] ?? null;
    if (!$id) {
        sendResponse(['status' => 'error', 'message' => 'ID required']);
    }
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
    $stmt->execute([$id]);
    sendResponse(['status' => 'success', 'message' => 'Product deleted']);
}

// ========== MEMBERS CRUD ==========
if ($action === 'members') {
    $stmt = $pdo->query("SELECT * FROM members ORDER BY id DESC");
    $data = $stmt->fetchAll();
    sendResponse(['status' => 'success', 'data' => $data]);
}

if ($action === 'save_member') {
    $id = $_POST['id'] ?? null;
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $accountType = $_POST['account_type'] ?? 'jobseeker';
    $password = $_POST['password'] ?? '';

    if (empty($name) || empty($email) || empty($phone)) {
        sendResponse(['status' => 'error', 'message' => 'Name, email, and phone required']);
    }

    if (!preg_match('/^[0-9]+$/', $phone)) {
        sendResponse(['status' => 'error', 'message' => 'Phone must contain only digits']);
    }

    $pdo->beginTransaction();
    try {
        if ($id) {
            // Update member
            $stmt = $pdo->prepare("UPDATE members SET name = ?, email = ?, phone = ?, account_type = ? WHERE id = ?");
            $stmt->execute([$name, $email, $phone, $accountType, $id]);

            // Optionally update user password if provided
            if (!empty($password)) {
                // Get user_id from member
                $stmtUser = $pdo->prepare("SELECT user_id FROM members WHERE id = ?");
                $stmtUser->execute([$id]);
                $userId = $stmtUser->fetchColumn();
                if ($userId) {
                    $hashed = password_hash($password, PASSWORD_DEFAULT);
                    $stmtUpdate = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                    $stmtUpdate->execute([$hashed, $userId]);
                }
            }
        } else {
            // Insert new member: also need to create user
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmtUser = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, 'user')");
            $stmtUser->execute([$email, $hashed]);
            $userId = $pdo->lastInsertId();

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

            // Free subscription
            $stmtSub = $pdo->prepare("INSERT INTO subscriptions (user_id, plan, status) VALUES (?, 'Free', 'active')");
            $stmtSub->execute([$userId]);
        }
        $pdo->commit();
        sendResponse(['status' => 'success', 'message' => 'Member saved']);
    } catch (Exception $e) {
        $pdo->rollBack();
        sendResponse(['status' => 'error', 'message' => 'Save failed: ' . $e->getMessage()]);
    }
}

if ($action === 'delete_member') {
    $id = $_GET['id'] ?? null;
    if (!$id) {
        sendResponse(['status' => 'error', 'message' => 'ID required']);
    }
    // Get user_id to delete user and cascade
    $stmt = $pdo->prepare("SELECT user_id FROM members WHERE id = ?");
    $stmt->execute([$id]);
    $userId = $stmt->fetchColumn();
    if ($userId) {
        // Delete user (ON DELETE CASCADE will remove member and subscriptions)
        $stmtDel = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmtDel->execute([$userId]);
        sendResponse(['status' => 'success', 'message' => 'Member deleted']);
    } else {
        sendResponse(['status' => 'error', 'message' => 'Member not found']);
    }
}

// ========== SUBSCRIPTIONS CRUD ==========
if ($action === 'subscriptions') {
    $stmt = $pdo->query("SELECT * FROM subscriptions ORDER BY id DESC");
    $data = $stmt->fetchAll();
    sendResponse(['status' => 'success', 'data' => $data]);
}

if ($action === 'save_subscription') {
    $id = $_POST['id'] ?? null;
    $userId = $_POST['user_id'] ?? null;
    $plan = $_POST['plan'] ?? 'Free';
    $status = $_POST['status'] ?? 'active';

    if (!$userId) {
        sendResponse(['status' => 'error', 'message' => 'User ID required']);
    }

    if ($id) {
        $stmt = $pdo->prepare("UPDATE subscriptions SET user_id = ?, plan = ?, status = ? WHERE id = ?");
        $stmt->execute([$userId, $plan, $status, $id]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan, status) VALUES (?, ?, ?)");
        $stmt->execute([$userId, $plan, $status]);
    }
    sendResponse(['status' => 'success', 'message' => 'Subscription saved']);
}

if ($action === 'delete_subscription') {
    $id = $_GET['id'] ?? null;
    if (!$id) {
        sendResponse(['status' => 'error', 'message' => 'ID required']);
    }
    $stmt = $pdo->prepare("DELETE FROM subscriptions WHERE id = ?");
    $stmt->execute([$id]);
    sendResponse(['status' => 'success', 'message' => 'Subscription deleted']);
}

// ========== JOBS CRUD ==========
if ($action === 'jobs') {
    $stmt = $pdo->query("SELECT * FROM jobs ORDER BY id DESC");
    $data = $stmt->fetchAll();
    sendResponse(['status' => 'success', 'data' => $data]);
}

if ($action === 'save_job') {
    $id = $_POST['id'] ?? null;
    $title = $_POST['title'] ?? '';
    $company = $_POST['company'] ?? '';
    $location = $_POST['location'] ?? '';
    $status = $_POST['status'] ?? 'active';

    if (empty($title) || empty($company)) {
        sendResponse(['status' => 'error', 'message' => 'Title and company required']);
    }

    if ($id) {
        $stmt = $pdo->prepare("UPDATE jobs SET title = ?, company = ?, location = ?, status = ? WHERE id = ?");
        $stmt->execute([$title, $company, $location, $status, $id]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO jobs (title, company, location, status) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $company, $location, $status]);
    }
    sendResponse(['status' => 'success', 'message' => 'Job saved']);
}

if ($action === 'delete_job') {
    $id = $_GET['id'] ?? null;
    if (!$id) {
        sendResponse(['status' => 'error', 'message' => 'ID required']);
    }
    $stmt = $pdo->prepare("DELETE FROM jobs WHERE id = ?");
    $stmt->execute([$id]);
    sendResponse(['status' => 'success', 'message' => 'Job deleted']);
}

// ========== APPLICATIONS CRUD ==========
if ($action === 'applications') {
    $stmt = $pdo->query("SELECT * FROM applications ORDER BY id DESC");
    $data = $stmt->fetchAll();
    sendResponse(['status' => 'success', 'data' => $data]);
}

if ($action === 'delete_application') {
    $id = $_GET['id'] ?? null;
    if (!$id) {
        sendResponse(['status' => 'error', 'message' => 'ID required']);
    }
    $stmt = $pdo->prepare("DELETE FROM applications WHERE id = ?");
    $stmt->execute([$id]);
    sendResponse(['status' => 'success', 'message' => 'Application deleted']);
}

// ========== SETTINGS ==========
if ($action === 'get_settings') {
    $stmt = $pdo->query("SELECT * FROM settings LIMIT 1");
    $settings = $stmt->fetch();
    sendResponse(['status' => 'success', 'data' => $settings]);
}

if ($action === 'update_settings') {
    // Expect POST with key-value pairs
    $allowedKeys = ['site_name', 'currency', 'contact_email', 'meta_title', 'meta_description', 'keywords', 'smtp_host', 'smtp_port', 'smtp_username', 'smtp_password'];
    $updates = [];
    foreach ($_POST as $key => $value) {
        if (in_array($key, $allowedKeys)) {
            $updates[$key] = $value;
        }
    }
    if (empty($updates)) {
        sendResponse(['status' => 'error', 'message' => 'No valid settings provided']);
    }

    // We'll update by replacing the single row (assume id=1)
    $setClause = [];
    $params = [];
    foreach ($updates as $key => $value) {
        $setClause[] = "$key = ?";
        $params[] = $value;
    }
    $sql = "UPDATE settings SET " . implode(', ', $setClause) . " WHERE id = 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    sendResponse(['status' => 'success', 'message' => 'Settings updated']);
}

// ========== EXPORT CSV ==========
if ($action === 'export') {
    $type = $_GET['type'] ?? '';
    $allowed = ['products', 'members', 'subscriptions', 'jobs', 'applications'];
    if (!in_array($type, $allowed)) {
        sendResponse(['status' => 'error', 'message' => 'Invalid export type']);
    }

    // Fetch data
    $stmt = $pdo->query("SELECT * FROM $type");
    $data = $stmt->fetchAll();
    if (empty($data)) {
        sendResponse(['status' => 'error', 'message' => 'No data to export']);
    }

    // CSV headers
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $type . '_export.csv"');

    $output = fopen('php://output', 'w');
    // Add column headers
    $headers = array_keys($data[0]);
    fputcsv($output, $headers);
    foreach ($data as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit();
}

// ========== DEFAULT ==========
sendResponse(['status' => 'error', 'message' => 'Unknown action']);
?>
Back to Directory=ceiIENDB`