<?php
require_once 'databaseConnection.php';
$mysqli = db_connect();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $invoiceNumber = trim($_POST['invoiceNumber']);
    $jobNumber = trim($_POST['jobNumber'] ?? '');

    if (empty($invoiceNumber) || empty($jobNumber)) {
        echo "empty";
        exit;
    }

    // Check for duplicate
    $stmt = $mysqli->prepare("SELECT id FROM invoiceRegistry WHERE invoiceNumber = ?");
    $stmt->bind_param("s", $invoiceNumber);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        echo "duplicate";
        exit;
    }
    $stmt->close();

    // Insert with both invoiceNumber and jobNumber
    $stmt = $mysqli->prepare("INSERT INTO invoiceRegistry (invoiceNumber, jobNumber) VALUES (?, ?)");
    $stmt->bind_param("ss", $invoiceNumber, $jobNumber);
    if ($stmt->execute()) {
        echo "success";
    } else {
        echo "error";
    }

    $stmt->close();
    $mysqli->close();
}
?>
