<?php
require 'db_config.php';

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

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

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

        // If no duplicate, update the customer
        $sql = "UPDATE customers SET name=?, email=?, phone=?, address=?, category=?, productInterest=?, note=?, lastContact=?, is_active=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $phone, $address, $category, $productInterest, $note, $lastContact, $isActive, $id]);

        echo json_encode(['status' => 'success', 'message' => 'Customer updated successfully.']);

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