<?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'] ?? '';

    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 suppliers WHERE phone = ?");
        $stmt_check->execute([$phone]);
        if ($stmt_check->fetch()) {
            echo json_encode(['status' => 'error', 'message' => 'This phone number is already registered for another supplier.']);
            exit();
        }

        $sql = "INSERT INTO suppliers (name, email, phone, address, category, productInterest, note) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $phone, $address, $category, $productInterest, $note]);
        
        echo json_encode(['status' => 'success', 'message' => 'Supplier added.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?>