<?php
include_once 'shikanisha.kts.php';

// Get the data from the AJAX request
$name = $_POST['fullname'];
$shop = $_POST['shop'];
$phone = $_POST['phone'];
$amount= 0;

// Check if client already exists
$sql_check = "SELECT * FROM customers WHERE full_name = '$name' AND phone_number = '$phone'";
$result = $conn->query($sql_check);

if ($result->num_rows > 0) {
    // Client already exists
    $response = array("success" => false, "message" => "Client with name $name and phone number $phone already exists.");
} else {
    // Insert the data into the database
    $sql_insert = "INSERT INTO customers (full_name, location, phone_number) VALUES ('$name', '$shop', '$phone')";

    if ($conn->query($sql_insert) === TRUE) {
        // Successfully inserted new client

        // Assuming you have the $amount and $client_id variables defined
        // Insert data into client_acc table using the retrieved client_id
        $sql_acc = "INSERT INTO client_acc (amount_owed, client_id) VALUES ('$amount', LAST_INSERT_ID())";

        if ($conn->query($sql_acc) === TRUE) {
            // Data insertion into client_acc table was successful
            $response = array("success" => true, "message" => "Client added successfully.");
        } else {
            // Error occurred during data insertion into client_acc table
            $response = array("success" => false, "error" => $conn->error);
        }
    } else {
        // Error occurred during data insertion into customers table
        $response = array("success" => false, "error" => $conn->error);
    }

    // Close the database connection
    $conn->close();
}

// Send the JSON response back to the client
header("Content-Type: application/json");
echo json_encode($response);
?>
