<?php
declare(strict_types=1);

/**
 * Soft-delete helper functions.
 * Include via: require_once __DIR__ . '/../helpers/soft_delete.php';
 */

/**
 * Mark a record as soft-deleted.
 */
function softDelete(PDO $pdo, string $table, int $id): bool
{
    $stmt = $pdo->prepare("UPDATE `{$table}` SET deleted_at = NOW() WHERE id = :id AND deleted_at IS NULL");
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->rowCount() > 0;
}

/**
 * Restore a soft-deleted record.
 */
function restoreRecord(PDO $pdo, string $table, int $id): bool
{
    $stmt = $pdo->prepare("UPDATE `{$table}` SET deleted_at = NULL WHERE id = :id AND deleted_at IS NOT NULL");
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->rowCount() > 0;
}

/**
 * Restore a soft-deleted record with a composite key.
 */
function restoreRecordWhere(PDO $pdo, string $table, string $where, array $params): bool
{
    $stmt = $pdo->prepare("UPDATE `{$table}` SET deleted_at = NULL WHERE {$where} AND deleted_at IS NOT NULL");
    $stmt->execute($params);
    return $stmt->rowCount() > 0;
}

/**
 * Returns 'AND {alias.}deleted_at IS NULL' for use in SQL WHERE clauses.
 * Pass the table alias (e.g. 'v', 'd', 'mj') or '' for no prefix.
 *
 * Example: $sql = "SELECT * FROM vehicles v WHERE v.vehicle_status = 'Active'" . notDeleted('v');
 */
function notDeleted(string $alias = ''): string
{
    return $alias === '' ? ' AND deleted_at IS NULL' : " AND {$alias}.deleted_at IS NULL";
}
