<?php
include 'db.php';

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $firstName = $_POST['firstName'] ?? '';
    $surname = $_POST['surname'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $email = $_POST['email'] ?? '';
    $zone = $_POST['zone'] ?? '';
    $cooperativeName = $_POST['cooperativeName'] ?? '';
    $accountNumber = $_POST['accountNumber'] ?? '';
    $bankName = $_POST['bankName'] ?? '';
    $investmentUnits = $_POST['investmentUnits'] ?? '';
    $otherAmount = $_POST['otherAmount'] ?? null;
    $address = $_POST['address'] ?? null;

    // Validate required fields
    if (empty($firstName) || empty($surname) || empty($phone) || empty($email) || empty($zone) || empty($investmentUnits)) {
        echo json_encode(['success' => false, 'message' => 'Please fill in all required fields.']);
        exit;
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Please enter a valid email address.']);
        exit;
    }

    // Validate phone number (at least 10 digits)
    if (strlen(preg_replace('/\D/', '', $phone)) < 10) {
        echo json_encode(['success' => false, 'message' => 'Please enter a valid phone number.']);
        exit;
    }

    // Check if email or phone number already exists
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM registrations WHERE email = ? OR phone = ?");
    $stmt->bind_param("ss", $email, $phone);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->fetch_assoc()['count'] > 0) {
        echo json_encode(['success' => false, 'message' => 'Email or phone number already exists.']);
        exit;
    }

    // If custom amount, validate it
    if ($investmentUnits === 'custom' && (empty($otherAmount) || !is_numeric($otherAmount))) {
        echo json_encode(['success' => false, 'message' => 'Please enter a valid custom amount.']);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO registrations (first_name, surname, phone, email, address, investment_units, other_amount, zone, cooperative_name, account_number, bank_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssdssss", $firstName, $surname, $phone, $email, $address, $investmentUnits, $otherAmount, $zone, $cooperativeName, $accountNumber, $bankName);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Registration successful!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $stmt->error]);
    }

    $stmt->close();
    $conn->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
