<?php

namespace UltraguardPro\modules\auto_updater\db;

if ( ! defined( 'ABSPATH' ) ) { exit; }

use UltraguardPro\db\BaseTable;
use UltraguardPro\core\DatabaseCrud;

class UpdateLogTable extends BaseTable {

    protected $table_name  = 'ultraguard_update_log';
    protected $cache_group = 'ultraguard_update_log';

    public function get_defaults(): array {
        return [
            'id'             => 0,
            'component_type' => '',
            'component_slug' => '',
            'component_name' => '',
            'old_version'    => '',
            'new_version'    => '',
            'status'         => 'pending',
            'trigger_type'   => 'auto',
            'error_message'  => '',
            'snapshot_path'  => '',
            'rolled_back_at' => '',
            'updated_by'     => 0,
            'created_at'     => '',
            'updated_at'     => '',
        ];
    }

    protected function validate_data( $data ) {
        return $this->validate_required( (array) $data, [ 'component_type', 'component_slug', 'component_name', 'old_version', 'new_version', 'status' ] ) ? $data : false;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $key => $value ) {
            if ( 'updated_by' === $key ) {
                $out[ $key ] = absint( $value );
            } elseif ( in_array( $key, [ 'error_message', 'snapshot_path' ], true ) ) {
                $out[ $key ] = sanitize_textarea_field( (string) $value );
            } else {
                $out[ $key ] = is_string( $value ) ? sanitize_text_field( $value ) : $value;
            }
        }
        return $out;
    }

    public function count_by_status( string $status ): int {
        return (int) $this->count( [ 'status' => $status ], 'id', false );
    }

    public function count_created_since( string $relative_time, array $conditions = [] ): int {
        $cutoff = gmdate( 'Y-m-d H:i:s', strtotime( $relative_time ) );
        return DatabaseCrud::count_since( 'ultraguard_update_log', $conditions, 'created_at', $cutoff );
    }

    public function get_recent( int $limit = 50, string $date_field = 'created_at', array $conditions = [], bool $use_cache = true ): array {
        return (array) $this->get_by(
            $conditions,
            max( 1, min( 200, $limit ) ),
            $date_field,
            'DESC',
            0,
            $use_cache
        );
    }

    public function get_monthly_type_breakdown(): array {
        $cutoff = gmdate( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
        $rows = DatabaseCrud::get_grouped_count_since( 'ultraguard_update_log', 'component_type', [], 'created_at', $cutoff, 20 );

        return array_map(
            static function ( $row ): array {
                if ( is_object( $row ) ) {
                    return [
                        'component_type' => (string) ( $row->component_type ?? '' ),
                        'total'          => (int) ( $row->count ?? 0 ),
                    ];
                }

                return [
                    'component_type' => (string) ( $row['component_type'] ?? '' ),
                    'total'          => (int) ( $row['count'] ?? 0 ),
                ];
            },
            (array) $rows
        );
    }
}
