<?php
require 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $email = $_POST['email'] ?? '';
    $address = $_POST['address'] ?? '';
    $category = $_POST['category'] ?? '';
    $productInterest = $_POST['productInterest'] ?? '';
    $note = $_POST['note'] ?? '';
    $isActive = isset($_POST['is_active']) ? $_POST['is_active'] : 0; // Added handling

    if (empty($name) || empty($phone)) {
        echo json_encode(['status' => 'error', 'message' => 'Name and Phone are required.']);
        exit();
    }

    try {
        // Check for duplicate phone number
        $stmt_check = $pdo->prepare("SELECT id FROM customers WHERE phone = ?");
        $stmt_check->execute([$phone]);
        if ($stmt_check->fetch()) {
            echo json_encode(['status' => 'error', 'message' => 'This phone number is already registered.']);
            exit();
        }

        // If no duplicate, insert new customer
        $sql = "INSERT INTO customers (name, email, phone, address, category, productInterest, note, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $phone, $address, $category, $productInterest, $note, $isActive]);
        $newId = $pdo->lastInsertId();

        // Fetch the newly created customer to return it
        $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
        $stmt->execute([$newId]);
        $newCustomer = $stmt->fetch(PDO::FETCH_ASSOC);

        echo json_encode(['status' => 'success', 'message' => 'Customer added.', 'data' => $newCustomer]);

    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?>