<?php namespace Tussendoor\Reloadify\Controllers\AbandonedCart;

use ReloadifyScoped\Illuminate\Database\QueryException;
use Tussendoor\Reloadify\Controllers\Controller;
use Tussendoor\Reloadify\Helpers\Request;
use Tussendoor\Reloadify\Models\AbandonedCart\AbandonedCartMeta;

class AbandonedCartMetaController extends Controller
{

    /**
     * Wrapper method to update or create new cart meta based on given values
     *
     * @since 1.3.0 We save meta data individually and users could empty a checkout field. When that happens we remove the meta data from the database
     * @since 1.4.0 Touch the parent to update the timestamp
     *
     * @param  array $data
     * @param  int $cart_id
     * @return bool
     */
    protected function updateCreateCartMeta(array $data, int $cart_id) : bool
    {
        $metaModel = null; // Initialize $metaModel to ensure it's in scope for the final check

        foreach ($data as $key => $value) {
            try {
                // Remove entry when value is empty
                if (empty($value)) {
                    AbandonedCartMeta::where('cart_id', $cart_id)
                        ->where('meta_key', $key)
                        ->delete();

                    continue;
                }

                $metaModel = AbandonedCartMeta::updateOrCreate(
                    [
                        'cart_id'   => $cart_id,
                        'meta_key'  => $key,
                    ],
                    [
                        'meta_value' => $value,
                    ]
                );

            } catch (QueryException $e) {
                // Log the query exception with context
                error_log('QueryException in updateCreateCartMeta: ' . $e->getMessage());
                return false;
            }
        }

        // Ensure $metaModel and $metaModel->cart are not null before calling touch()
        // We log a warning if $metaModel->cart is null because we're unsure of the impact
        // and want to track occurrences to better understand and address potential issues.
        if ($metaModel && $metaModel->cart) {
            // Update the cart timestamp
            $metaModel->cart->touch();
        } else {
            // Log the situation as a warning for further investigation
            error_log('Warning: Attempted to touch cart on null in updateCreateCartMeta. Cart ID: ' . $cart_id . '. This indicates the cart related to the provided cart_id does not exist or is not properly linked. Further investigation is needed to understand the impact and address the root cause.');
        }

        return true;
    }

    /**
     * Save meta data for logged in users
     * @see AbandonedCartController@saveOrUpdateAbandonedCart()
     *
     * @param  mixed $cart_id
     * @return bool
     */
    public function parseUserMetaData(int $cart_id) : bool
    {
        $user = wp_get_current_user();

        $userData = [
            'first_name'    => $user->user_firstname ?: $user->data->display_name,
            'last_name'     => $user->user_lastname ?: '',
            'email'         => sanitize_email($user->data->user_email),
            'language'      => $this->getCurrentLocale($user->data->ID),
        ];

        $userData = array_filter($userData);

        return $this->updateCreateCartMeta($userData, $cart_id);
    }

    /**
     * Save meta data for customers that have allready entered their information
     * @see AbandonedCartController@saveOrUpdateAbandonedCart()
     *
     * @param  int $cart_id
     * @return bool
     */
    public function parseCustomerMetaData(int $cart_id) : bool
    {
        $customer   = WC()->session->get('customer');
        $request    = new Request($customer);

        $userData = [
            'first_name'    => $request->getString('first_name'),
            'last_name'     => $request->getString('last_name'),
            'email'         => $request->getEmail('email'),
            'language'      => $this->getCurrentLocale(),
        ];

        $userData = array_filter($userData);

        return $this->updateCreateCartMeta($userData, $cart_id);
    }

}
