<?php
ob_start();
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';
ob_end_clean();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) { echo json_encode(['success' => false]); exit; }

$d    = json_decode(file_get_contents('php://input'), true);
$name = trim($d['supplier_name'] ?? '');
if (!$name) { echo json_encode(['success' => false, 'message' => 'Name required']); exit; }

$stmt = $conn->prepare("
    INSERT INTO pharmacy_suppliers (supplier_name, contact_person, phone, email, kra_pin, created_by)
    VALUES (?, ?, ?, ?, ?, ?)
");
$contact = trim($d['contact_person'] ?? '');
$phone   = trim($d['phone']   ?? '');
$email   = trim($d['email']   ?? '');
$kra     = trim($d['kra_pin'] ?? '');
$uid     = (int)$_SESSION['user_id'];
$stmt->bind_param('sssssi', $name, $contact, $phone, $email, $kra, $uid);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'supplier_id' => $conn->insert_id]);
} else {
    echo json_encode(['success' => false, 'message' => 'DB error: ' . $conn->error]);
}
$stmt->close();