<?php

namespace UltraguardPro\modules\compliance_reports\db;

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

use UltraguardPro\db\BaseTable;

class GeneratedReportsTable extends BaseTable {

    protected $table_name  = 'ultraguard_generated_reports';
    protected $cache_group = 'ultraguard_generated_reports';

    public function get_defaults(): array {
        return [
            'id'              => 0,
            'report_type'     => '',
            'report_title'    => '',
            'date_range_from' => '',
            'date_range_to'   => '',
            'format'          => 'html',
            'file_path'       => '',
            'file_size'       => 0,
            'generated_by'    => 0,
            'status'          => 'pending',
            'sections'        => '',
            'error_message'   => '',
            'created_at'      => '',
        ];
    }

    protected function validate_data( $data ) {
        return $this->validate_required( (array) $data, [ 'report_type', 'report_title', 'date_range_from', 'date_range_to' ] ) ? $data : false;
    }

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

    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 );
    }
}
