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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/agrifood.cloud/public_html/api.php

<?php
// api.php - AGRI-Food RESTful Backend API
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

// Database credentials
$host = 'localhost';
$dbname = 'u456810272_agrifood';
$user = 'u456810272_agrifood';
$pass = 'Global@#980';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $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(['status' => 'error', 'message' => 'Database connection failed: ' . $e->getMessage()]);
    exit();
}

// Start session for login state
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Helper to check if user is logged in (for dashboard-only actions)
function requireLogin() {
    if (!isset($_SESSION['user_id'])) {
        sendResponse('error', 'Unauthorized. Please login.');
    }
}

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

switch ($action) {
    // -------------------- LOGIN --------------------
    case 'login':
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        if (!$email || !$password) {
            sendResponse('error', 'Email and password are required.');
        }
        $stmt = $pdo->prepare("SELECT id, email, password, role FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        if (!$user) {
            sendResponse('error', 'Invalid email or password.');
        }
        // Plain text password check (as per instructions for admin, but we also support hashed passwords for registered users)
        if ($user['password'] === $password || password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['role'] = $user['role'];
            sendResponse('success', 'Login successful.', ['user_id' => $user['id']]);
        } else {
            sendResponse('error', 'Invalid email or password.');
        }
        break;

    // -------------------- REGISTER --------------------
    case 'register':
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        if (!$name || !$email || !$phone || !$password) {
            sendResponse('error', 'All fields are required.');
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            sendResponse('error', 'Invalid email address.');
        }
        if (!preg_match('/^[0-9]{10,15}$/', $phone)) {
            sendResponse('error', 'Phone number must be numeric and between 10-15 digits.');
        }
        if (strlen($password) < 8) {
            sendResponse('error', 'Password must be at least 8 characters.');
        }

        // Hash the password (except for admin seed)
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $role = 'member';

        // Insert into users
        $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, ?)");
        try {
            $stmt->execute([$email, $hashedPassword, $role]);
            $userId = $pdo->lastInsertId();
        } catch (PDOException $e) {
            // Email might already exist in users (we allow multiple registrations with same email per instruction)
            // So we just fetch the existing user id and proceed
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            $existing = $stmt->fetch();
            if (!$existing) {
                sendResponse('error', 'Registration failed: ' . $e->getMessage());
            }
            $userId = $existing['id'];
        }

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

        // Create a free subscription for the member
        $memberId = $pdo->lastInsertId();
        $stmt = $pdo->prepare("INSERT INTO subscriptions (member_id, plan, status, created_at) VALUES (?, 'Free', 'active', NOW())");
        $stmt->execute([$memberId]);

        sendResponse('success', 'Registration successful. Please login.');
        break;

    // -------------------- LOGOUT --------------------
    case 'logout':
        session_destroy();
        header('Location: index.html');
        exit();

    // -------------------- PRODUCTS CRUD --------------------
    case 'get_products':
        requireLogin();
        $stmt = $pdo->query("SELECT id, name, price, status, created_at FROM products ORDER BY id DESC");
        $products = $stmt->fetchAll();
        sendResponse('success', 'Products retrieved.', ['products' => $products]);
        break;

    case 'add_product':
        requireLogin();
        $name = trim($_POST['name'] ?? '');
        $price = floatval($_POST['price'] ?? 0);
        if (!$name || $price <= 0) {
            sendResponse('error', 'Valid name and price required.');
        }
        $stmt = $pdo->prepare("INSERT INTO products (name, price, status, created_at) VALUES (?, ?, 'active', NOW())");
        $stmt->execute([$name, $price]);
        sendResponse('success', 'Product added.', ['id' => $pdo->lastInsertId()]);
        break;

    case 'update_product':
        requireLogin();
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $price = floatval($_POST['price'] ?? 0);
        if (!$id || !$name || $price <= 0) {
            sendResponse('error', 'Invalid product data.');
        }
        $stmt = $pdo->prepare("UPDATE products SET name = ?, price = ? WHERE id = ?");
        $stmt->execute([$name, $price, $id]);
        sendResponse('success', 'Product updated.');
        break;

    case 'delete_product':
        requireLogin();
        $id = intval($_POST['id'] ?? 0);
        if (!$id) {
            sendResponse('error', 'Product ID required.');
        }
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);
        sendResponse('success', 'Product deleted.');
        break;

    // -------------------- MEMBERS CRUD --------------------
    case 'get_members':
        requireLogin();
        $stmt = $pdo->query("SELECT id, user_id, name, email, phone, created_at FROM members ORDER BY id DESC");
        $members = $stmt->fetchAll();
        sendResponse('success', 'Members retrieved.', ['members' => $members]);
        break;

    case 'add_member':
        requireLogin();
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        if (!$name || !$email || !$phone || !$password) {
            sendResponse('error', 'All fields required.');
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            sendResponse('error', 'Invalid email.');
        }
        if (!preg_match('/^[0-9]{10,15}$/', $phone)) {
            sendResponse('error', 'Phone must be numeric 10-15 digits.');
        }
        // Create user account
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, 'member')");
        $stmt->execute([$email, $hashed]);
        $userId = $pdo->lastInsertId();
        // Create member
        $stmt = $pdo->prepare("INSERT INTO members (user_id, name, email, phone, created_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$userId, $name, $email, $phone]);
        $memberId = $pdo->lastInsertId();
        // Free subscription
        $stmt = $pdo->prepare("INSERT INTO subscriptions (member_id, plan, status, created_at) VALUES (?, 'Free', 'active', NOW())");
        $stmt->execute([$memberId]);
        sendResponse('success', 'Member added.', ['id' => $memberId]);
        break;

    case 'update_member':
        requireLogin();
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        if (!$id || !$name || !$email || !$phone) {
            sendResponse('error', 'All fields required.');
        }
        $stmt = $pdo->prepare("UPDATE members SET name = ?, email = ?, phone = ? WHERE id = ?");
        $stmt->execute([$name, $email, $phone, $id]);
        sendResponse('success', 'Member updated.');
        break;

    case 'delete_member':
        requireLogin();
        $id = intval($_POST['id'] ?? 0);
        if (!$id) {
            sendResponse('error', 'Member ID required.');
        }
        // Get user_id first
        $stmt = $pdo->prepare("SELECT user_id FROM members WHERE id = ?");
        $stmt->execute([$id]);
        $member = $stmt->fetch();
        if ($member) {
            // Delete user (cascade will delete member and subscriptions if foreign keys set)
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$member['user_id']]);
        }
        sendResponse('success', 'Member deleted.');
        break;

    // -------------------- SUBSCRIPTIONS CRUD --------------------
    case 'get_subscriptions':
        requireLogin();
        $stmt = $pdo->query("SELECT s.id, s.member_id, m.name as member_name, s.plan, s.status, s.created_at FROM subscriptions s JOIN members m ON s.member_id = m.id ORDER BY s.id DESC");
        $subs = $stmt->fetchAll();
        sendResponse('success', 'Subscriptions retrieved.', ['subscriptions' => $subs]);
        break;

    case 'add_subscription':
        requireLogin();
        $memberId = intval($_POST['member_id'] ?? 0);
        $plan = trim($_POST['plan'] ?? '');
        if (!$memberId || !$plan) {
            sendResponse('error', 'Member ID and plan required.');
        }
        $stmt = $pdo->prepare("INSERT INTO subscriptions (member_id, plan, status, created_at) VALUES (?, ?, 'active', NOW())");
        $stmt->execute([$memberId, $plan]);
        sendResponse('success', 'Subscription added.', ['id' => $pdo->lastInsertId()]);
        break;

    case 'update_subscription':
        requireLogin();
        $id = intval($_POST['id'] ?? 0);
        $status = trim($_POST['status'] ?? '');
        if (!$id || !$status) {
            sendResponse('error', 'ID and status required.');
        }
        $stmt = $pdo->prepare("UPDATE subscriptions SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);
        sendResponse('success', 'Subscription updated.');
        break;

    case 'delete_subscription':
        requireLogin();
        $id = intval($_POST['id'] ?? 0);
        if (!$id) {
            sendResponse('error', 'Subscription ID required.');
        }
        $stmt = $pdo->prepare("DELETE FROM subscriptions WHERE id = ?");
        $stmt->execute([$id]);
        sendResponse('success', 'Subscription deleted.');
        break;

    // -------------------- SETTINGS --------------------
    case 'get_settings':
        requireLogin();
        $stmt = $pdo->query("SELECT * FROM settings");
        $settings = [];
        while ($row = $stmt->fetch()) {
            $settings[$row['key']] = $row['value'];
        }
        sendResponse('success', 'Settings retrieved.', ['settings' => $settings]);
        break;

    case 'update_settings':
        requireLogin();
        $data = $_POST['settings'] ?? [];
        if (!is_array($data)) {
            sendResponse('error', 'Invalid settings data.');
        }
        foreach ($data as $key => $value) {
            $stmt = $pdo->prepare("INSERT INTO settings (`key`, `value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `value` = ?");
            $stmt->execute([$key, $value, $value]);
        }
        sendResponse('success', 'Settings updated.');
        break;

    // -------------------- DASHBOARD STATS --------------------
    case 'dashboard_stats':
        requireLogin();
        $stats = [];

        // Products count
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM products WHERE status = 'active'");
        $stats['products'] = intval($stmt->fetch()['count']);

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

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

        // Revenue (mock: sum of product prices * 10 as an example)
        $stmt = $pdo->query("SELECT SUM(price) as total FROM products");
        $totalProductsPrice = floatval($stmt->fetch()['total'] ?? 0);
        $stats['revenue'] = round($totalProductsPrice * 10, 2);

        sendResponse('success', 'Dashboard stats retrieved.', $stats);
        break;

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