<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Admin\PersonalData;

use BookiFlex\Core\Contract\PluginInterface;

defined( 'ABSPATH' ) || exit;

class DataEraser
{
    private readonly PluginInterface $plugin;

    public function __construct(PluginInterface $plugin)
    {
        $this->plugin = $plugin;
        $this->init();
    }

    private function init(): void
    {
        $this->plugin->addFilter('wp_privacy_personal_data_erasers', [$this, 'registerEraser']);
    }

    public function registerEraser(array $exporters): array
    {
        $exporters['bookiflex'] = [
            'eraser_friendly_name' => __('BookiFlex Plugin Data', 'bookiflex'),
            'callback'               => [__CLASS__, 'eraserPersonalData'],
        ];
        return $exporters;
    }

    public static function erasePersonalData(string $email_address, int $page = 1): array
    {
        if (!function_exists('bookiflex')) {
            return [];
        }

        // Get plugin instance
        $plugin = bookiflex();
        if (!$plugin) {
            return [
                'items_removed'  => false,
                'items_retained' => false,
                'messages'       => [],
                'done'           => true,
            ];
        }

        $container = $plugin->getContainer();
        $customerRepo = $container->get(\BookiFlex\Core\Repository\CustomerRepository::class);
        $orm = $container->get(\Cycle\ORM\ORMInterface::class);

        // Find customer by email
        $customer = $customerRepo->findByEmail($email_address);
        if (!$customer) {
            return [
                'items_removed'  => false,
                'items_retained' => false,
                'messages'       => [],
                'done'           => true,
            ];
        }

        try {
            $reservationRepo = $container->get(\BookiFlex\Core\Repository\ReservationRepository::class);

            // Get all reservations for this customer
            $reservations = $reservationRepo->select()
                ->where('customer_id', $customer->getId())
                ->fetchAll();

            // Anonymize reservations
            foreach ($reservations as $reservation) {
                $reservation->setSpecialRequest('');
            }

            // Anonymize customer data
            $customerId = $customer->getId();
            $timestamp = time();

            $customer->setFirstName('Anonymous');
            $customer->setLastName('User ' . $customerId);
            $customer->setEmail('deleted-user-' . $customerId . '-' . $timestamp . '@anonymized.local');
            $customer->setPhone('');
            $customer->setMetadata([
                'address' => '',
                'city' => '',
                'country' => '',
                'postalCode' => '',
                'notes' => '',
            ]);

            // Persist all changes
            $entityManager = $orm->getHeap();
            foreach ($reservations as $reservation) {
                $entityManager->persist($reservation);
            }
            $entityManager->persist($customer);
            $entityManager->run();

            return [
                'items_removed'  => true,
                'items_retained' => true,
                'messages'       => [
                    __('Customer personal data has been anonymized.', 'bookiflex'),
                    __('Financial records have been retained for legal and accounting purposes.', 'bookiflex'),
                ],
                'done'           => true,
            ];
        } catch (\Exception $e) {
            return [
                'items_removed'  => false,
                'items_retained' => false,
                'messages'       => [
                    __('An error occurred while erasing personal data.', 'bookiflex'),
                ],
                'done'           => true,
            ];
        }
    }
}
