<?php
namespace GriffinForms\Admin\Actions;

use \GriffinForms\Traits\Singleton;

class Submissions extends \GriffinForms\Admin\Actions\Format
{
    use Singleton;

    /**
     * Register WordPress hooks for submission lifecycle events.
     */
    public function register()
    {
        add_action('griffinforms_before_delete_submission', [$this, 'beforeDeleteSubmission'], 10, 1);
        add_action('griffinforms_before_delete_submission', [$this, 'deleteSubmissionRevisions'], 20, 1);
    }

    /**
     * Runs before a submission is deleted. If the Files Storage setting
     * "delete attachments on submission delete" is enabled, remove all
     * attached files for the given submission and their DB rows.
     *
     * @param int $submission_id The submission ID.
     * @return void
     */
    public function beforeDeleteSubmission($submission_id)
    {
        $submission_id = (int) $submission_id;
        if ($submission_id <= 0) {
            if (!empty($this->log)) {
                $this->log->add(
                    'error',
                    'file',
                    $submission_id,
                    get_current_user_id(),
                    '[Actions\Submissions] Invalid submission_id received for beforeDeleteSubmission',
                    'submission'
                );
            }
            return;
        }

        // Settings gate (default: off unless explicitly enabled)
        $delete_attachments = 0;
        if (!empty($this->settings) && method_exists($this->settings, 'getOption')) {
            $opt = $this->settings->getOption('files_delete_on_submission_delete');
            $delete_attachments = (int) $opt === 1 ? 1 : 0;
        }

        if (!$delete_attachments) {
            if (!empty($this->log)) {
                $this->log->add(
                    'info',
                    'file',
                    $submission_id,
                    get_current_user_id(),
                    '[Actions\Submissions] Skipping attachment deletion for submission_id=' . $submission_id . ' (setting disabled)',
                    'submission'
                );
            }
            return;
        }

        if (empty($this->sql) || !method_exists($this->sql, 'deleteAttachmentsBySubmissionId')) {
            if (!empty($this->log)) {
                $this->log->add(
                    'error',
                    'file',
                    $submission_id,
                    get_current_user_id(),
                    '[Actions\Submissions] SQL layer not ready or method missing: deleteAttachmentsBySubmissionId',
                    'submission'
                );
            }
            return;
        }

        try {
            $deleted_rows = $this->sql->deleteAttachmentsBySubmissionId($submission_id);

            if ($deleted_rows && $deleted_rows > 0) {
                if (!empty($this->log)) {
                    $this->log->add(
                        'success',
                        'file',
                        $submission_id,
                        get_current_user_id(),
                        '[Actions\Submissions] Deleted ' . (int) $deleted_rows . ' attachment(s) for submission_id=' . $submission_id,
                        'submission'
                    );
                }
            } else {
                if (!empty($this->log)) {
                    $this->log->add(
                        'info',
                        'file',
                        $submission_id,
                        get_current_user_id(),
                        '[Actions\Submissions] No attachments found to delete for submission_id=' . $submission_id,
                        'submission'
                    );
                }
            }
        } catch (\Throwable $e) {
            if (!empty($this->log)) {
                $this->log->add(
                    'error',
                    'file',
                    $submission_id,
                    get_current_user_id(),
                    '[Actions\Submissions] Exception while deleting attachments for submission_id=' . $submission_id . ': ' . $e->getMessage(),
                    'submission'
                );
            }
        }
    }

    public function deleteSubmissionRevisions(int $submission_id): void
    {
        $submission_id = (int) $submission_id;
        if ($submission_id <= 0) {
            return;
        }

        try {
            $history = \GriffinForms\Includes\Pipelines\SubmissionHistoryManager::getInstance();
            $history->deleteRevisionsBySubmissionId($submission_id);
        } catch (\Throwable $e) {
            if (!empty($this->log)) {
                $this->log->add(
                    'error',
                    'submission',
                    $submission_id,
                    get_current_user_id(),
                    '[Actions\Submissions] Exception while deleting revisions for submission_id=' . $submission_id . ': ' . $e->getMessage(),
                    'submission'
                );
            }
        }
    }
}