<?php
require_once 'db/config.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $personId = $_POST['id'];
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $company_name = $_POST['company_name'];
    $phone = $_POST['phone'];
    $role = $_POST['role'] ?? 'guest';
    $functions = isset($_POST['functions']) ? $_POST['functions'] : [];
    $password = $_POST['password'];
    $bni_group_id = isset($_POST['bni_group_id']) && !empty($_POST['bni_group_id']) ? $_POST['bni_group_id'] : null;

    // New fields
    $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)) {
        http_response_code(422);
        echo json_encode(['error' => ['message' => 'First name, last name, and email are required.'], 'correlation_id' => uniqid()]);
        exit;
    }

    // Only members can be in a group
    if ($role !== 'member') {
        $bni_group_id = null;
    }

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

        // Handle file uploads
        $upload_dir = 'uploads/people/' . $personId . '/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $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 = [];

        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[$db_column_name] = $destination;
                }
            }
        }

        // Prepare SQL for updating person details
        $sql_parts = [
            'first_name = ?', 'last_name = ?', 'email = ?', 'company_name = ?', 'phone = ?',
            'role = ?', 'bni_group_id = ?', 'nip = ?', 'industry = ?', 'company_size_revenue = ?',
            'business_description = ?'
        ];
        $params = [
            $first_name, $last_name, $email, $company_name, $phone, $role, $bni_group_id,
            $nip, $industry, $company_size_revenue, $business_description
        ];

        if (!empty($password)) {
            $sql_parts[] = 'password = ?';
            $params[] = password_hash($password, PASSWORD_DEFAULT);
        }

        foreach ($file_paths as $column => $path) {
            $sql_parts[] = "$column = ?";
            $params[] = $path;
        }

        $sql = "UPDATE people SET " . implode(', ', $sql_parts) . " WHERE id = ?";
        $params[] = $personId;

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        // Update functions
        $stmt = $pdo->prepare("DELETE FROM user_functions WHERE user_id = ?");
        $stmt->execute([$personId]);

        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();
        $_SESSION['success_message'] = 'Osoba zaktualizowana pomyślnie.';

    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log('Update failed: ' . $e->getMessage());
        $_SESSION['error_message'] = "Błąd podczas aktualizacji osoby: " . $e->getMessage();
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log('File upload or other error: ' . $e->getMessage());
        $_SESSION['error_message'] = "Błąd: " . $e->getMessage();
    }

    header('Location: index.php');
    exit();
}