<?php

namespace GriffinForms\Frontend\Ajax;

trait ManageDbSubmission
{
    protected function truncateSubmissions($form_id)
    {
        $form = new \GriffinForms\Items\Form();
        $form->loadItem($this->data['form']);
        $save_entries = (!empty($form->getProp('save_entries'))) ? $form->getProp('save_entries') : 'AllEntries';
        
        $method = 'keep' . str_replace('_','', $save_entries);
        $this->$method($form_id);
    }

    protected function keepAllEntries($form_id)
    {
        return;
    }

    protected function keepNoEntries($form_id)
    {
        $this->keepSubmissions(0, $form_id);
    }

    protected function keepRecentTen($form_id)
    {
        $this->keepSubmissions(10, $form_id);
    }

    protected function keepRecentFifty($form_id)
    {
        $this->keepSubmissions(50, $form_id);
    }

    protected function keepRecentHundred($form_id)
    {
        $this->keepSubmissions(100, $form_id);
    }

    protected function keepRecentThousand($form_id)
    {
        $this->keepSubmissions(1000, $form_id);
    }

    protected function keepSubmissions($limit, $form_id)
    {
        $sql = \GriffinForms\Frontend\Sql\Form::getInstance();
        $count = $sql->submissionCount($form_id, 1);
    
        if ($count > $limit) {
            $to_delete = $count - $limit;
            $table = esc_sql($this->config->getTable('submission'));
    
            global $wpdb;
            $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM %i WHERE form_id = %d AND status = 1 LIMIT %d",
                    $table,
                    $form_id,
                    $to_delete
                )
            );
        }
    }
}