<?php

require_once "config.php";

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if (isset($_GET['cemail'])) {
            $cemail = $_GET['cemail'];

            $stmt = $conn->prepare("SELECT cVersi FROM tbmember WHERE cemail = ?");
            $stmt->bind_param("s", $cemail);
            $stmt->execute();
            
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            echo json_encode($result);
        } else {
            echo json_encode(['error' => 'Email is required']);
        }
        break;

    case 'POST':
        // Ambil data JSON yang dikirim melalui POST
        $input = json_decode(file_get_contents('php://input'), true);

        if (isset($input['cemail']) && isset($input['cVersi'])) {
            $cemail = $input['cemail'];
            $cVersi = $input['cVersi'];

            // Buat query untuk memperbarui data di tabel tbmember
            $stmt = $conn->prepare("UPDATE tbmember SET cVersi = ? WHERE cemail = ?");
            $stmt->bind_param("ss", $cVersi, $cemail);
            
            if ($stmt->execute()) {
                echo json_encode(['message' => 'Data updated successfully']);
            } else {
                echo json_encode(['error' => 'Failed to update data']);
            }

            $stmt->close();
        } else {
            echo json_encode(['error' => 'cemail and cVersi are required']);
        }
        break;

    default:
        echo json_encode(['error' => 'Invalid request method']);
        break;
}

// Menutup koneksi database
$conn->close();

?>
