<?php
require_once __DIR__ . '/db.php';

function add_timeline_message($contract_id, $body, $type = 'text', $direction = 'outgoing', $user_id = null, $username = null) {
    $pdo = get_db_connection();
    
    if (!$user_id && isset($_SESSION['user_id'])) {
        $user_id = $_SESSION['user_id'];
        $username = $_SESSION['username'];
    }

    $stmt = $pdo->prepare("INSERT INTO contract_messages (contract_id, user_id, username, direction, body, type) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$contract_id, $user_id, $username, $direction, $body, $type]);
    return $pdo->lastInsertId();
}

function add_timeline_attachment($contract_id, $message_id, $file_path, $file_name, $file_type, $user_id = null) {
    $pdo = get_db_connection();
    
    if (!$user_id && isset($_SESSION['user_id'])) {
        $user_id = $_SESSION['user_id'];
    }

    $stmt = $pdo->prepare("INSERT INTO contract_attachments (contract_id, message_id, file_path, file_name, file_type, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$contract_id, $message_id, $file_path, $file_name, $file_type, $user_id]);
}

function log_status_change($contract_id, $old_status, $new_status, $user_id = null, $username = null) {
    $body = "Status alterado de '$old_status' para '$new_status'";
    return add_timeline_message($contract_id, $body, 'status_change', 'outgoing', $user_id, $username);
}
