<?php
require_once 'lib/ErrorHandler.php';
register_error_handler();
require_once 'lib/i18n.php';
require_once 'db/config.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => ['message' => t('error.method_not_allowed', 'Niedozwolona metoda.')], 'correlation_id' => uniqid()]);
    exit;
}

$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$company_name = $_POST['company_name'] ?? null;
$phone = $_POST['phone'] ?? null;
$role = $_POST['role'] ?? 'guest';
$functions = isset($_POST['functions']) ? (array)$_POST['functions'] : [];
$bni_group_id = isset($_POST['bni_group_id']) && !empty($_POST['bni_group_id']) ? $_POST['bni_group_id'] : null;

$nip = $_POST['nip'] ?? null;
$industry = $_POST['industry'] ?? null;
$company_size_revenue = $_POST['company_size_revenue'] ?? null;
$business_description = $_POST['business_description'] ?? null;

if (empty($first_name) || empty($last_name) || empty($email) || empty($password)) {
    http_response_code(422);
    echo json_encode(['error' => ['message' => t('error.missing_fields', 'Imię, nazwisko, email i hasło są wymagane.')], 'correlation_id' => uniqid()]);
    exit;
}

if ($role !== 'member') {
    $bni_group_id = null;
}

$pdo = db();
try {
    $pdo->beginTransaction();

    $sql = 'INSERT INTO people (first_name, last_name, email, password, company_name, phone, role, bni_group_id, nip, industry, company_size_revenue, business_description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$first_name, $last_name, $email, password_hash($password, PASSWORD_DEFAULT), $company_name, $phone, $role, $bni_group_id, $nip, $industry, $company_size_revenue, $business_description]);
    $personId = $pdo->lastInsertId();

    $upload_dir = 'uploads/people/' . $personId . '/';
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0777, true) && !is_dir($upload_dir)) {
            throw new RuntimeException(sprintf('Directory "%s" was not created', $upload_dir));
        }
    }

    $file_fields = [
        'company_logo' => 'company_logo_path',
        'person_photo' => 'person_photo_path',
        'gains_sheet' => 'gains_sheet_path',
        'top_wanted_contacts' => 'top_wanted_contacts_path',
        'top_owned_contacts' => 'top_owned_contacts_path'
    ];
    $file_paths_to_update = [];

    foreach ($file_fields as $form_field_name => $db_column_name) {
        if (isset($_FILES[$form_field_name]) && $_FILES[$form_field_name]['error'] == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES[$form_field_name]['tmp_name'];
            $original_name = basename($_FILES[$form_field_name]['name']);
            $file_ext = pathinfo($original_name, PATHINFO_EXTENSION);
            $new_filename = uniqid($form_field_name . '_', true) . '.' . $file_ext;
            $destination = $upload_dir . $new_filename;

            if (move_uploaded_file($tmp_name, $destination)) {
                $file_paths_to_update[$db_column_name] = $destination;
            } else {
                throw new RuntimeException("Failed to move uploaded file for {$form_field_name}.");
            }
        }
    }

    if (!empty($file_paths_to_update)) {
        $sql_parts = [];
        $params = [];
        foreach ($file_paths_to_update as $column => $path) {
            $sql_parts[] = "$column = ?";
            $params[] = $path;
        }
        $params[] = $personId;
        $sql = "UPDATE people SET " . implode(', ', $sql_parts) . " WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
    }

    if (!empty($functions)) {
        $sql = "INSERT INTO user_functions (user_id, function_id) VALUES (?, ?)";
        $stmt = $pdo->prepare($sql);
        foreach ($functions as $functionId) {
            $stmt->execute([$personId, $functionId]);
        }
    }
    
    $pdo->commit();

    echo json_encode(['success' => true, 'person_id' => $personId, 'message' => 'Person created successfully.']);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    if ($e->errorInfo[1] == 1062) {
        http_response_code(409); // Conflict
        echo json_encode(['error' => ['message' => t('error.email_exists', 'Konto z tym adresem email już istnieje.')], 'correlation_id' => uniqid()]);
    } else {
        throw $e; // Re-throw to be caught by the global error handler
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    throw $e; // Re-throw to be caught by the global error handler
}