<?php
session_start();
include('../config/db.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $full_name = $_POST['full_name'];
    $email = $_POST['email'];
    $phone_number = $_POST['phone_number'];
    $address = $_POST['address'];
    $gender = $_POST['gender'];

    try {
        // Check if the email is provided and already exists
        if (!empty($email)) {
            $checkEmailQuery = "SELECT COUNT(*) FROM customers WHERE email = :email";
            $stmt = $pdo->prepare($checkEmailQuery);
            $stmt->bindParam(':email', $email);
            $stmt->execute();
            $emailCount = $stmt->fetchColumn();

            if ($emailCount > 0) {
                echo 'Error: The email address is already registered.'; // Response to AJAX
                exit; // Stop further execution
            }
        }

        // Insert new customer
        $query = "INSERT INTO customers (full_name, email, phone_number, address, gender, created_at) 
                  VALUES (:full_name, :email, :phone_number, :address, :gender, NOW())";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':full_name', $full_name);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':phone_number', $phone_number);
        $stmt->bindParam(':address', $address);
        $stmt->bindParam(':gender', $gender);

        if ($stmt->execute()) {
            echo 'success'; // Response to AJAX
        } else {
            echo 'Error: Could not add customer.'; // Response to AJAX
        }
    } catch (PDOException $e) {
        echo 'Error: ' . $e->getMessage(); // Response to AJAX
    }
}
?>
