<?php

namespace PloverCRM\Modules\Reminders;

use PloverCRM\Core\AbstractModule;

/**
 * Reminders Module
 * 
 * Allows users to schedule reminder notifications for contacts.
 * Mobile app fetches reminders and schedules local notifications.
 */
class RemindersModule extends AbstractModule
{
    protected $id = 'reminders';
    protected $dependencies = [];

    public function getMetadata(): array
    {
        return [
            'name' => 'Reminder Notifications',
            'description' => 'Schedule reminder notifications for contacts',
            'version' => '1.0.0',
            'author' => 'WebPlover',
            'icon' => '🔔',
            'required' => false,
        ];
    }

    public function register(): void
    {
        $settings = new Settings();
        $settings->register();

        add_action('rest_api_init', [$this, 'registerEndpoints']);

        // Handle contact deletion - cascade delete reminders
        add_action('plover_crm/contact_deleted', [$this, 'handleContactDeleted']);
        add_action('fluent_crm/contact_deleted', [$this, 'handleContactDeleted']);
        add_action('before_delete_post', [$this, 'handlePostDeleted']);
    }

    public function boot(): void
    {
        Database\Schema::maybeCreateTable();
    }

    public function isEnabled(): bool
    {
        $crm = $this->container->get('crm');
        return $crm->isAvailable();
    }

    public function registerEndpoints(): void
    {
        $remindersEndpoint = new Endpoints\RemindersEndpoint($this->container);
        $this->registerModuleEndpoint($remindersEndpoint);

        $settingsEndpoint = new Endpoints\SettingsEndpoint($this->container);
        $this->registerModuleEndpoint($settingsEndpoint);
    }

    public function handleContactDeleted($contactId): void
    {
        Services\ReminderManager::deleteByContactId((int) $contactId);
    }

    public function handlePostDeleted($postId): void
    {
        if (get_post_type($postId) === 'plover_crm_contact') {
            Services\ReminderManager::deleteByContactId((int) $postId);
        }
    }
}
