<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

// Function to sanitize input
function sanitize_input($input) {
    return htmlspecialchars(stripslashes(trim($input)));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_id'], $_POST['auth'])) {
    include 'db/config.php';

    // Retrieve and sanitize input
    $inputs = ['user_id', 'auth', 'denomination', 'church_work'];
    $data = [];
    foreach ($inputs as $field) {
        $data[$field] = sanitize_input($_POST[$field] ?? '');
    }

    // Validate required fields
    foreach ($inputs as $field) {
        if (empty($data[$field])) {
            echo json_encode(['status' => false, 'success' => "$field is required"]);
            exit;
        }
    }

    date_default_timezone_set("Africa/Lagos");
    $date_reg = date("Y-m-d H:i:s");

    try {
        // Check user existence
        $user_query = $con->prepare("SELECT user_id FROM users WHERE user_id = ? AND auth = ?");
        $user_query->bind_param("ss", $data['user_id'], $data['auth']);
        $user_query->execute();
        $user_result = $user_query->get_result();

        if ($user_result->num_rows === 0) {
            echo json_encode(['status' => false, 'success' => 'User not found']);
            exit;
        }

        // Update query
        $query1 = "
            UPDATE users 
            SET denomination = ? 
            WHERE user_id = ? AND auth = ?
        ";
        $stmt1 = $con->prepare($query1);
        $stmt1->bind_param(
            "sss", 
            $data['denomination'], 
            $data['user_id'], 
            $data['auth']
        );

        if ($stmt1->execute()) {
            echo json_encode([
                'status' => true,
                'user_id' => $data['user_id'],  
                'success' => 'Profile updated'
            ]);
        } else {
            echo json_encode([
                'status' => false, 
                'success' => 'Update failed: ' . $stmt1->error
            ]);
        }

    } catch (Exception $e) {
        echo json_encode(['status' => false, 'success' => $e->getMessage()]);
    } finally {
        $con->close();
    }
} else {
    echo json_encode(['status' => false, 'success' => 'Invalid request']);
}
?>
