<?php
require 'conn.php';
session_start();

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate inputs
    $fullname = sanitizeInput($_POST['fullname']);
    $phone = sanitizeInput($_POST['phone']);
    $email = sanitizeInput($_POST['email']);
    $password = sanitizeInput($_POST['password']);
    $confirm_password = sanitizeInput($_POST['confirm_password']);
    $transaction_pin = sanitizeInput($_POST['transaction_pin']);
    $address = sanitizeInput($_POST['address']);

    // Validate inputs
    $errors = [];

    if (empty($fullname)) {
        $errors[] = "Fullname is required.";
    }
    if (empty($phone)) {
        $errors[] = "Phone number is required.";
    }
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid email is required.";
    }
    if (empty($password)) {  // Fixed Syntax Error
        $errors[] = "Password is required.";
    }
    if ($password !== $confirm_password) {
        $errors[] = "Passwords do not match.";
    }
    if (empty($transaction_pin)) {  // Fixed Syntax Error
        $errors[] = "Transaction pin is required.";
    }
    if (empty($address)) {
        $errors[] = "Address is required.";
    }

    // If no errors, proceed with registration
    if (empty($errors)) {
        // Check if email or phone already exists
        $check_query = "SELECT * FROM jamaa WHERE email = ? OR phone = ?";
        $stmt = $conn->prepare($check_query);
        $stmt->bind_param("ss", $email, $phone);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            echo json_encode(["status" => "error", "message" => "Email or phone number already exists."]);
        } else {
            // Hash the password and transaction pin
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $hashed_pin = password_hash($transaction_pin, PASSWORD_DEFAULT);

            // Insert user into the database
            $insert_query = "INSERT INTO jamaa (fullname, phone, email, password, transaction_pin, address, type) VALUES (?, ?, ?, ?, ?, ?, 'user')";
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("ssssss", $fullname, $phone, $email, $hashed_password, $hashed_pin, $address);

            if ($stmt->execute()) {
                echo json_encode(["status" => "success", "message" => "Registration successful!"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Registration failed. Please try again."]);
            }
            $stmt->close();
        }
        exit;
    }
}
?>
