<?php
// api/register.php
require_once 'database.php';
require_once 'auth.php';
//require_once '../config.php';

// Verify the JWT token
$token = $_SERVER['HTTP_AUTHORIZATION'];
$user = verify_token($token);

if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid token.']);
    exit;
}

// Retrieve form data
$title = $_POST['title'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$zone = $_POST['zone'];
$church = $_POST['church'];
$kingschat_number = $_POST['kingschat_number'];
$email = $_POST['email'];
$phone_number = $_POST['phone_number'];
$year_joined_church = $_POST['year_joined_church'];
$water_baptized = $_POST['water_baptized'];
$year_graduated_foundation = $_POST['year_graduated_foundation'];
$position_in_church = $_POST['position_in_church'];

// Validate and sanitize the data
if (
    empty($title) || empty($first_name) || empty($last_name) || empty($zone) || empty($church) || empty($kingschat_number) ||
    empty($email) || empty($phone_number) || empty($year_joined_church) || empty($water_baptized) || empty($year_graduated_foundation) ||
    empty($position_in_church)
) {
    http_response_code(400);
    echo json_encode(['error' => 'All fields are required.']);
    exit;
}

$title = filter_var($title, FILTER_SANITIZE_STRING);
$first_name = filter_var($first_name, FILTER_SANITIZE_STRING);
$last_name = filter_var($last_name, FILTER_SANITIZE_STRING);
$zone = filter_var($zone, FILTER_SANITIZE_STRING);
$church = filter_var($church, FILTER_SANITIZE_STRING);
$kingschat_number = filter_var($kingschat_number, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$phone_number = filter_var($phone_number, FILTER_SANITIZE_STRING);
$year_joined_church = filter_var($year_joined_church, FILTER_SANITIZE_NUMBER_INT);
$water_baptized = filter_var($water_baptized, FILTER_SANITIZE_STRING);
$year_graduated_foundation = filter_var($year_graduated_foundation, FILTER_SANITIZE_NUMBER_INT);
$position_in_church = filter_var($position_in_church, FILTER_SANITIZE_STRING);

// Hash the password
//$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Store the registration data in the database
$stmt = $pdo->prepare("INSERT INTO users (title, first_name, last_name, zone, church, kingschat_number, email, phone_number, year_joined_church, water_baptized, year_graduated_foundation, position_in_church) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$title, $first_name, $last_name, $zone, $church, $kingschat_number, $email, $phone_number, $year_joined_church, $water_baptized, $year_graduated_foundation, $position_in_church]);

http_response_code(201);