<?php
require_once '../includes/auth.php';
require_once '../db.php';

if (!hasPermission('master_sales')) { echo json_encode(['status'=>'error','msg'=>'Unauthorized']); exit; }

header('Content-Type: application/json');

$name          = trim($_POST['name'] ?? '');
$phone         = trim($_POST['phone'] ?? '');
$email         = trim($_POST['email'] ?? '');
$customer_type = $_POST['customer_type'] ?? 'B2C';
$gstin         = strtoupper(trim($_POST['gstin'] ?? ''));
$state_code    = trim($_POST['state_code'] ?? '');
$state         = trim($_POST['state'] ?? '');
$address       = trim($_POST['address'] ?? '');
if ($name === '') {
    echo json_encode(['status'=>'error','msg'=>'Client name required']);
    exit;
}

$stmt = $conn->prepare("
    INSERT INTO clients (name, phone, email, customer_type, gstin, state_code, state, address, status, company_id)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
");
$stmt->bind_param("ssssssssi", $name, $phone, $email, $customer_type, $gstin, $state_code, $state, $address, $cid);

if ($stmt->execute()) {
    echo json_encode(['status' => 'ok', 'id' => $stmt->insert_id, 'name' => $name]);
} else {
    echo json_encode(['status'=>'error','msg'=>'DB insert failed']);
}
