<?php
/**
 * POS Quick Add API
 */

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

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

require_once '../../include/con_data.php';
require_once '../../include/secondary_ids.php';

$user_id = $_SESSION['user_id'];
// In this system, $_SESSION['user_id'] already contains the US_xxx string,
// so we don't need to look it up using the integer ID.
$user_secondary_id = (strpos($user_id, 'US_') === 0) ? $user_id : getUserSecondaryId($conn, $user_id);

try {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input)
        throw new Exception('Invalid JSON');

    $type = $input['type'] ?? '';
    $name = trim($input['name'] ?? '');
    $shop_id = intval($input['shop_id'] ?? 0);

    if (!$name || !$shop_id)
        throw new Exception('ຂໍ້ມູນບໍ່ຄົບ');

    if ($type === 'company') {
        $stmt = $conn->prepare("INSERT INTO shipping_companies (shop_id, company_name, is_active, created_by, created_at) VALUES (?, ?, 1, ?, NOW())");
        $stmt->bind_param("iss", $shop_id, $name, $user_secondary_id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'id' => $conn->insert_id]);
        } else {
            throw new Exception($stmt->error);
        }
    } elseif ($type === 'branch') {
        $stmt = $conn->prepare("INSERT INTO shipping_branches (shop_id, branch_name, is_active, created_by, created_at) VALUES (?, ?, 1, ?, NOW())");
        $stmt->bind_param("iss", $shop_id, $name, $user_secondary_id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'id' => $conn->insert_id]);
        } else {
            throw new Exception($stmt->error);
        }
    } elseif ($type === 'customer') {
        $phone = trim($input['phone'] ?? '');
        $stmt = $conn->prepare("INSERT INTO customers (shop_id, name, phone, is_active, created_by, created_at) VALUES (?, ?, ?, 1, ?, NOW())");
        $stmt->bind_param("isss", $shop_id, $name, $phone, $user_secondary_id);
        if ($stmt->execute()) {
            $new_id = $conn->insert_id;
            echo json_encode(['success' => true, 'id' => $new_id]);
        } else {
            throw new Exception($stmt->error);
        }
    } else {
        throw new Exception('Invalid Type');
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>