<?php
namespace App\Repositories;

use App\Database\Connection;
use PDO;

/**
 * Field Audit Log Repository
 * Tracks all changes to fields for auditing and compliance
 */
class FieldAuditLogRepository
{
    private Connection $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    /**
     * Log a field change
     */
    public function logChange(array $data): int
    {
        $pdo = $this->db->getPdo();
        
        $sql = "INSERT INTO field_audit_logs 
               (entity_type, entity_id, field_name, old_value, new_value, actor_didar_id, actor_name, created_at)
               VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $data['entity_type'] ?? 'unknown',
            $data['entity_id'] ?? '',
            $data['field_name'] ?? '',
            $data['old_value'] ?? null,
            $data['new_value'] ?? null,
            $data['actor_didar_id'] ?? null,
            $data['actor_name'] ?? null
        ]);
        
        return (int)$pdo->lastInsertId();
    }

    /**
     * Log multiple field changes at once
     */
    public function logChanges(string $entityType, string $entityId, array $changes, ?string $actorDidarId = null, ?string $actorName = null): void
    {
        foreach ($changes as $fieldName => $values) {
            $this->logChange([
                'entity_type' => $entityType,
                'entity_id' => $entityId,
                'field_name' => $fieldName,
                'old_value' => $values['old'] ?? null,
                'new_value' => $values['new'] ?? null,
                'actor_didar_id' => $actorDidarId,
                'actor_name' => $actorName
            ]);
        }
    }

    /**
     * Get audit history for an entity
     */
    public function getByEntity(string $entityType, string $entityId, int $limit = 100): array
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare(
            "SELECT * FROM field_audit_logs 
             WHERE entity_type = ? AND entity_id = ? 
             ORDER BY created_at DESC 
             LIMIT ?"
        );
        $stmt->execute([$entityType, $entityId, $limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Get audit history for a specific field across entities
     */
    public function getByField(string $fieldName, int $limit = 100): array
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare(
            "SELECT * FROM field_audit_logs 
             WHERE field_name = ? 
             ORDER BY created_at DESC 
             LIMIT ?"
        );
        $stmt->execute([$fieldName, $limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Get audit history by actor
     */
    public function getByActor(string $actorDidarId, int $limit = 100): array
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare(
            "SELECT * FROM field_audit_logs 
             WHERE actor_didar_id = ? 
             ORDER BY created_at DESC 
             LIMIT ?"
        );
        $stmt->execute([$actorDidarId, $limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Get recent audit logs
     */
    public function getRecent(int $limit = 100, ?string $entityType = null): array
    {
        $pdo = $this->db->getPdo();
        
        $sql = "SELECT * FROM field_audit_logs";
        $params = [];
        
        if ($entityType) {
            $sql .= " WHERE entity_type = ?";
            $params[] = $entityType;
        }
        
        $sql .= " ORDER BY created_at DESC LIMIT ?";
        $params[] = $limit;
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Get count of changes for a field in a date range
     */
    public function getChangeCount(string $fieldName, ?string $fromDate = null, ?string $toDate = null): int
    {
        $pdo = $this->db->getPdo();
        
        $sql = "SELECT COUNT(*) FROM field_audit_logs WHERE field_name = ?";
        $params = [$fieldName];
        
        if ($fromDate) {
            $sql .= " AND created_at >= ?";
            $params[] = $fromDate;
        }
        
        if ($toDate) {
            $sql .= " AND created_at <= ?";
            $params[] = $toDate;
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return (int)$stmt->fetchColumn();
    }
}








