<?php
require __DIR__ . '/config.php'; 

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

// Create database connection
$conn = getDbConnection();

// Read JSON input
$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['org_name'], $data['email'])) {
    $org_name = trim($data['org_name']);
    $email = trim($data['email']);

    // Validate input (No empty values)
    if (empty($org_name) || empty($email)) {
        echo json_encode(["success" => false, "message" => "Organization name and email are required."]);
        exit;
    }

    // Check for duplicates
    $check_stmt = $conn->prepare("SELECT org_id FROM organizations WHERE org_name = ? OR email = ?");
    $check_stmt->bind_param("ss", $org_name, $email);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows > 0) {
        echo json_encode(["success" => false, "message" => "Organization or Email already exists."]);
        exit;
    }
    $check_stmt->close();

    // Insert organization
    $stmt = $conn->prepare("INSERT INTO organizations (org_name, email, subscription_status) VALUES (?, ?, 'Active')");
    if (!$stmt) {
        echo json_encode(["success" => false, "message" => "SQL Error: " . $conn->error]);
        exit;
    }

    $stmt->bind_param("ss", $org_name, $email);
    
    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "Organization added successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Error: " . $stmt->error]);
    }

    $stmt->close();
} else {
    echo json_encode(["success" => false, "message" => "Invalid input"]);
}

$conn->close();
?>
