<?php
require_once dirname(__DIR__, 2) . '/includes/db.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $store_name    = trim($conn->real_escape_string($_POST['store_name'] ?? ''));
        $store_type_id = isset($_POST['store_type_id']) ? (int)$_POST['store_type_id'] : 0;

        if (empty($store_name) || $store_type_id <= 0) {
            throw new Exception("All core database parameters (Store Name and Type Mapping) are mandatory.");
        }

        // Integrity Verification: Ensure the mapped relational ID exists and is active
        $verify = $conn->prepare("SELECT id FROM store_types WHERE id = ? AND is_active = 1");
        $verify->bind_param("i", $store_type_id);
        $verify->execute();
        if ($verify->get_result()->num_rows === 0) {
            throw new Exception("Security Alert: Selected operational configuration type is invalid or suspended.");
        }
        $verify->close();

        // Unique Constraint Verification
        $check = $conn->prepare("SELECT id FROM stores WHERE LOWER(store_name) = LOWER(?)");
        $check->bind_param("s", $store_name);
        $check->execute();
        if ($check->get_result()->num_rows > 0) {
            throw new Exception("An inventory node with the exact identity '{$store_name}' already exists within the registry.");
        }
        $check->close();

        // Perform Transactional Write Layer (Strictly Independent of Departments)
        $stmt = $conn->prepare("INSERT INTO stores (store_name, store_type_id, is_active) VALUES (?, ?, 1)");
        $stmt->bind_param("si", $store_name, $store_type_id);
        
        if (!$stmt->execute()) {
            throw new Exception("System Database Operations Fault: " . $stmt->error);
        }
        
        $stmt->close();
        echo json_encode(['status' => 'success', 'message' => "Store <strong>{$store_name}</strong> successfully provisioned as an independent inventory node."]);

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