<?php

/**
 * Contact Forms Integration
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Integration;

use _121Digital\Connect\Core\Plugin;

/**
 * ContactForms Class
 *
 * Handles integration with various contact form plugins
 */
class ContactForms
{
    /**
     * Check if Metform tables exist
     *
     * @return bool
     */
    public function hasMetformTables(): bool
    {
        global $wpdb;
        $tableName = $wpdb->prefix . 'mf_submissions';
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '{$tableName}'") === $tableName;

        return $tableExists;
    }

    /**
     * Get Metform submissions
     *
     * @return array
     */
    public function getMetformSubmissions(): array
    {
        $args = [
            'post_type'      => 'metform-entry',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];

        $query = new \WP_Query($args);
        $processedMetformEntries = [];

        foreach ($query->posts as $metformEntryPost) {
            $metformEntry = get_post_meta($metformEntryPost->ID, 'metform_entries__form_data', true);
            array_push($processedMetformEntries, [
                'entry_id'   => $metformEntryPost->ID,
                'entry_data' => $metformEntry,
                'entry_date' => $metformEntryPost->post_date,
            ]);
        }

        return $processedMetformEntries;
    }

    /**
     * Get Metform submissions for today
     *
     * @return array
     */
    public function getMetformSubmissionsToday(): array
    {
        $today = date('Y-m-d');
        $args = [
            'post_type'      => 'metform-entry',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'orderby'        => 'date',
            'order'          => 'DESC',
            'date_query'     => [
                [
                    'after'     => $today . ' 00:00:00',
                    'before'    => $today . ' 23:59:59',
                    'inclusive' => true,
                ],
            ],
        ];

        $query = new \WP_Query($args);
        $processedMetformEntries = [];

        foreach ($query->posts as $metformEntryPost) {
            $rawMeta = get_post_meta($metformEntryPost->ID, 'metform_entries__form_data', true);
            $entryData = $rawMeta;

            $processedMetformEntries[] = [
                'entry_id'   => $metformEntryPost->ID,
                'entry_date' => $metformEntryPost->post_date,
                'entry_data' => $entryData,
            ];
        }

        return $processedMetformEntries;
    }

    /**
     * Get all contact form submissions
     *
     * @return array
     */
    public function getSubmissions(): array
    {
        $itemisedSubmissions = [];
        $metformSubmissions = $this->getMetformSubmissions();

        foreach ($metformSubmissions as $metformSubmission) {
            $metformSubmission['form_type'] = 'metform';
            array_push($itemisedSubmissions, $metformSubmission);
        }

        return $itemisedSubmissions;
    }

    /**
     * Get today's contact form submissions
     *
     * @return array
     */
    public function getSubmissionsToday(): array
    {
        $itemisedSubmissions = [];
        $metformSubmissions = $this->getMetformSubmissionsToday();

        foreach ($metformSubmissions as $metformSubmission) {
            $metformSubmission['form_type'] = 'metform';
            array_push($itemisedSubmissions, $metformSubmission);
        }

        return $itemisedSubmissions;
    }

    /**
     * Get contact info from form entry
     *
     * @param array $formEntry
     * @return string
     */
    public function getEntryFromInfo(array $formEntry): string
    {
        $entryFromInfo = 'Unknown';

        if (!isset($formEntry) || !isset($formEntry['entry_data'])) {
            return $entryFromInfo;
        }

        $formData = $formEntry['entry_data'];

        if ($formEntry['form_type'] == 'metform') {
            if (isset($formData['mf-email'])) {
                $entryFromInfo = $formData['mf-email'];
            } elseif (isset($formData['mf-first-name'])) {
                if (isset($formData['mf-last-name'])) {
                    $entryFromInfo = $formData['mf-first-name'] . ' ' . $formData['mf-last-name'];
                } else {
                    $entryFromInfo = $formData['mf-first-name'];
                }
            } elseif (isset($formData['mf-phone'])) {
                $entryFromInfo = $formData['mf-phone'];
            }
        }

        return $entryFromInfo;
    }

    /**
     * Encode URL parameters for form entry
     *
     * @param array $formEntry
     * @return string
     */
    public function encodeUrlParams(array $formEntry): string
    {
        try {
            $formEntryId = $formEntry['entry_id'];
            $formType = $formEntry['form_type'];

            $decodedData = json_encode([
                'form_type'     => $formType,
                'form_entry_id' => $formEntryId,
            ]);

            return base64_encode($decodedData);
        } catch (\Exception $e) {
            Plugin::die($e->getMessage());
        }
    }

    /**
     * Decode URL parameters for form entry
     *
     * @param string $urlParams
     * @return array
     */
    public function decodeUrlParams(string $urlParams): array
    {
        try {
            $decodedData = base64_decode($urlParams);
            $data = json_decode($decodedData, true);

            if (isset($data['form_type']) && isset($data['form_entry_id'])) {
                return [
                    'form_type'     => $data['form_type'],
                    'form_entry_id' => $data['form_entry_id'],
                ];
            }

            throw new \Exception('Provided contact form entry URL data is invalid.');
        } catch (\Exception $e) {
            Plugin::die($e->getMessage());
        }
    }

    /**
     * Get entry data
     *
     * @param array $entry
     * @return array
     */
    public function getEntry(array $entry): array
    {
        if ($entry['form_type'] == 'metform') {
            $entryId = $entry['form_entry_id'];
            $metformEntry = get_post_meta($entryId, 'metform_entries__form_data', true);
            $metformEntry['entry_id'] = $entryId;
            $metformEntry['entry_date'] = get_post($entryId)->post_date;
            return $metformEntry;
        } else {
            Plugin::die('Unsupported contact form type: ' . $entry['form_type']);
        }
    }
}
