<?php
require 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? 0;
    $name = $_POST['name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    
    if ($id == 0 || empty($name) || empty($phone)) {
        echo json_encode(['status' => 'error', 'message' => 'Valid ID, Name, and Phone are required.']);
        exit();
    }
    
    // All other fields are optional
    $email = $_POST['email'] ?? '';
    $address = $_POST['address'] ?? '';
    $category = $_POST['category'] ?? '';
    $productInterest = $_POST['productInterest'] ?? '';
    $note = $_POST['note'] ?? '';

    try {
        // Check for duplicate phone number belonging to another supplier
        $stmt_check = $pdo->prepare("SELECT id FROM suppliers 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 supplier.']);
            exit();
        }

        $sql = "UPDATE suppliers SET name=?, email=?, phone=?, address=?, category=?, productInterest=?, note=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $phone, $address, $category, $productInterest, $note, $id]);

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