<?php

namespace GriffinForms\Admin\Ajax;

class Lists extends \GriffinForms\Admin\Ajax\Format
{   
    public function deleteItem()
    {
        // Check if required $_POST values are set
        if (!isset($_POST['item_type']) || !isset($_POST['item_id']) || !isset($_POST['nonce'])) {
            echo esc_html(__('Error: Missing required data.', 'griffinforms-form-builder'));
            wp_die();
        }

        $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'delete_item');
        if ($nonce_status !== false) {

            $item_type = sanitize_text_field(wp_unslash($_POST['item_type']));
            $item_id = absint(wp_unslash($_POST['item_id']));
            $delete_submissions = isset($_POST['delete_submissions']) && wp_unslash($_POST['delete_submissions']) === '1';

            $sql_class = '\GriffinForms\Admin\Sql\\' . $item_type;
            $sql = $sql_class::getInstance();

            if ($item_type === 'form') {
                $delete = $sql->deleteForm($item_id, $delete_submissions);
            } else {
                $this->beforeDeleteItemActions($item_type, $item_id);
                $delete = $sql->deleteItemById($item_type, $item_id);
                $this->afterDeleteItemActions($item_type, $item_id, $delete);
            }

            echo esc_html($delete);
            wp_die();
        }

        wp_die();
    }    
    
    public function deleteItems()
    {
        // Check if required $_POST values are set
        if (!isset($_POST['item_type']) || !isset($_POST['item_ids']) || !isset($_POST['nonce'])) {
            echo esc_html(__('Error: Missing required data.', 'griffinforms-form-builder'));
            wp_die();
        }

        $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'delete_items');
        if ($nonce_status != false) {

            $item_type = sanitize_text_field(wp_unslash($_POST['item_type']));

            $sql_class = '\GriffinForms\Admin\Sql\\' . $item_type;
            $sql = $sql_class::getInstance();

            $item_ids = isset($_POST['item_ids']) && is_array($_POST['item_ids']) ? wp_unslash($_POST['item_ids']) : [];
            $item_ids = array_map('absint', $item_ids);
            
            $sql->table = $this->config->getTable($item_type);
            
            if (is_array($item_ids)) {
                foreach ($item_ids as $item_id) {
                    $this->beforeDeleteItemActions($item_type, $item_id);
                    $delete = $sql->deleteRow($item_id);
                    $this->afterDeleteItemActions($item_type, $item_id, $delete);
                }
            }
            
            echo true;
            wp_die();
        }
        wp_die();   
    }

    /**
     * Run pre-delete hooks for a given item type.
     *
     * @param string $item_type The type of item being deleted (e.g., 'submission').
     * @param int    $item_id   The item ID.
     */
    protected function beforeDeleteItemActions($item_type, $item_id)
    {
        if ($item_type === 'submission') {
            /**
             * Fire before a submission is deleted.
             *
             * @param int $item_id Submission ID.
             */
            do_action('griffinforms_before_delete_submission', $item_id);
        }
        // Future: add other item types here
    }

    /**
     * Run post-delete hooks for a given item type.
     *
     * @param string $item_type The type of item deleted (e.g., 'submission').
     * @param int    $item_id   The item ID.
     * @param bool   $result    Result of the delete operation.
     */
    protected function afterDeleteItemActions($item_type, $item_id, $result)
    {
        if ($item_type === 'submission') {
            /**
             * Fire after a submission is deleted.
             *
             * @param int  $item_id Submission ID.
             * @param bool $result  Result of delete operation.
             */
            do_action('griffinforms_after_delete_submission', $item_id, $result);

            if ($result) {
                $log = \GriffinForms\Log::getInstance();
                $log->deleteByItem('submission', $item_id);
            }
        }
        // Future: add other item types here
    }
    
    public function duplicateItem()
    {
        // Check if required $_POST values are set
        if (!isset($_POST['item_type']) || !isset($_POST['item_id']) || !isset($_POST['nonce'])) {
            echo wp_json_encode(array(
                'status' => false,
                'message' => __('Error: Missing required data.', 'griffinforms-form-builder')
            ));
            wp_die();
        }

        $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'duplicate_item');
        if ($nonce_status === false) {
            echo wp_json_encode(array(
                'status' => false,
                'message' => __('Error: Invalid nonce.', 'griffinforms-form-builder')
            ));
            wp_die();
        }

        $item_type = sanitize_text_field(wp_unslash($_POST['item_type']));
        $item_id = absint(wp_unslash($_POST['item_id']));

        // Verify user can manage this item type
        if (!current_user_can('manage_options')) {
            echo wp_json_encode(array(
                'status' => false,
                'message' => __('Error: Insufficient permissions.', 'griffinforms-form-builder')
            ));
            wp_die();
        }

        global $wpdb;
        $table = $this->config->getTable($item_type);

        // Get the original item
        $original_item = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $item_id));

        if (!$original_item) {
            echo wp_json_encode(array(
                'status' => false,
                'message' => __('Error: Item not found.', 'griffinforms-form-builder')
            ));
            wp_die();
        }

        // Create a copy of the item data
        $duplicate_data = (array) $original_item;

        // Remove the ID so a new one is created
        unset($duplicate_data['id']);

        // Handle name with smart suffix logic
        if (isset($duplicate_data['name'])) {
            $name = sanitize_text_field($duplicate_data['name']);

            // Check if name already ends with " ––copy" or " ––copy (n)"
            if (preg_match('/\s+––copy(\s*\(\d+\))?$/', $name)) {
                // Replace existing copy suffix with incremented number
                if (preg_match('/\s+––copy\s*\((\d+)\)$/', $name, $matches)) {
                    // Increment the copy number
                    $copy_num = (int) $matches[1] + 1;
                    $name = preg_replace('/\s+––copy\s*\(\d+\)$/', ' ––copy (' . $copy_num . ')', $name);
                } else {
                    // Convert " ––copy" to " ––copy (2)"
                    $name = preg_replace('/\s+––copy$/', ' ––copy (2)', $name);
                }
            } else {
                // First duplicate, just append ––copy
                $name = $name . ' ––copy';
            }

            $duplicate_data['name'] = $name;
        }

        // Update timestamps for the duplicate
        if (isset($duplicate_data['created'])) {
            $duplicate_data['created'] = current_time('mysql', true);
        }

        // Also update last_edited if it exists
        if (isset($duplicate_data['last_edited'])) {
            $duplicate_data['last_edited'] = current_time('mysql', true);
        }

        // For form themes, always treat duplicates as user-created presets
        if ($item_type === 'formtheme' && isset($duplicate_data['origin'])) {
            $duplicate_data['origin'] = 'user';
        }

        // Update author to current user
        if (isset($duplicate_data['author'])) {
            $duplicate_data['author'] = get_current_user_id();
        }

        // Use SQL class to insert the duplicate
        $sql_class = '\GriffinForms\Admin\Sql\\' . $item_type;
        $sql = $sql_class::getInstance();

        $new_item_id = $sql->insertData($duplicate_data);

        if (!$new_item_id) {
            echo wp_json_encode(array(
                'status' => false,
                'message' => __('Error: Failed to create duplicate.', 'griffinforms-form-builder')
            ));
            wp_die();
        }

        echo wp_json_encode(array(
            'status' => true,
            'message' => __('Theme duplicated successfully.', 'griffinforms-form-builder'),
            'new_item_id' => $new_item_id
        ));
        wp_die();
    }

    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_deleteItem', array($this, 'deleteItem'));
        add_action('wp_ajax_deleteItems', array($this, 'deleteItems'));
        add_action('wp_ajax_duplicateItem', array($this, 'duplicateItem'));
    }
}
