<?php

namespace PloverCRM\Modules\Reminders\Endpoints;

use PloverCRM\Common\CrmUserManager;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Reminders\Services\ReminderManager;
use PloverCRM\Common\Permissions;
use WP_REST_Request;

/**
 * Reminders REST API Endpoint
 * 
 * GET    /wp-json/plover-crm/v1/reminders           - List user's reminders
 * POST   /wp-json/plover-crm/v1/reminders           - Create a reminder
 * GET    /wp-json/plover-crm/v1/reminders/{id}      - Get single reminder
 * PUT    /wp-json/plover-crm/v1/reminders/{id}      - Update a reminder
 * DELETE /wp-json/plover-crm/v1/reminders/{id}      - Delete a reminder
 */
class RemindersEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/reminders(?:/(?P<id>\d+))?';
    }

    public function getMethod()
    {
        return ['GET', 'POST', 'PUT', 'DELETE'];
    }

    public function handle(WP_REST_Request $request)
    {
        $method = $request->get_method();
        $id = $request->get_param('id');

        switch ($method) {
            case 'GET':
                return $id ? $this->getReminder($id) : $this->listReminders($request);
            case 'POST':
                return $this->createReminder($request);
            case 'PUT':
                return $this->updateReminder($id, $request);
            case 'DELETE':
                return $this->deleteReminder($id);
            default:
                return $this->error('Method not allowed', 405);
        }
    }

    private function listReminders(WP_REST_Request $request)
    {
        $currentActor = CrmUserManager::getCurrentProfile();

        if (!$currentActor) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        $args = [
            'status' => $request->get_param('status') ?? 'pending',
            'contact_id' => $request->get_param('contact_id'),
            'from' => $request->get_param('from'),
            'to' => $request->get_param('to'),
            'page' => $request->get_param('page') ?? 1,
            'per_page' => $request->get_param('per_page') ?? 20,
        ];

        $result = ReminderManager::getByCrmUserId((int) $currentActor['id'], $args);

        return $this->success($result['reminders'], [
            'total' => $result['total'],
            'page' => (int) $args['page'],
            'per_page' => (int) $args['per_page'],
            'total_pages' => ceil($result['total'] / $args['per_page']),
        ]);
    }

    private function getReminder($id)
    {
        if (empty($id)) {
            return $this->error('Reminder ID is required', 400, 'missing_id');
        }

        $currentActor = CrmUserManager::getCurrentProfile();

        if (!$currentActor) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        $reminder = ReminderManager::getById((int) $id, (int) $currentActor['id']);

        if (!$reminder) {
            return $this->error('Reminder not found', 404, 'not_found');
        }

        return $this->success($reminder);
    }

    private function createReminder(WP_REST_Request $request)
    {
        $data = $request->get_json_params();
        $currentActor = CrmUserManager::getCurrentProfile();

        if (!$currentActor) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        if (empty($data['contact_id'])) {
            return $this->error('Contact ID is required', 400, 'missing_contact_id');
        }

        if (empty($data['scheduled_at'])) {
            return $this->error('Scheduled time is required', 400, 'missing_scheduled_at');
        }

        $crm = $this->container->get('crm');
        $contact = $crm->getContact((int) $data['contact_id']);

        if (!$contact) {
            return $this->error('Contact not found', 404, 'contact_not_found');
        }

        $contactOwnerId = $crm->getContactOwner((int) $data['contact_id']);
        if (!Permissions::canViewContact($contactOwnerId)) {
            return $this->error('You do not have permission to create reminders for this contact', 403, 'permission_denied');
        }

        $scheduledAt = $this->parseDateTime($data['scheduled_at']);
        if (!$scheduledAt) {
            return $this->error('Invalid scheduled_at format. Use ISO 8601 format (e.g., 2025-01-20T10:00:00Z)', 400, 'invalid_date_format');
        }

        $reminder = ReminderManager::create([
            'contact_id' => (int) $data['contact_id'],
            'crm_user_id' => (int) $currentActor['id'],
            'title' => $data['title'] ?? null,
            'note' => $data['note'] ?? null,
            'scheduled_at' => $scheduledAt,
        ]);

        if (!$reminder) {
            return $this->error('Failed to create reminder', 500, 'creation_failed');
        }

        return $this->success($reminder, ['created' => true], 201);
    }

    private function updateReminder($id, WP_REST_Request $request)
    {
        if (empty($id)) {
            return $this->error('Reminder ID is required', 400, 'missing_id');
        }

        $data = $request->get_json_params();
        $currentActor = CrmUserManager::getCurrentProfile();

        if (!$currentActor) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        if (isset($data['scheduled_at'])) {
            $scheduledAt = $this->parseDateTime($data['scheduled_at']);
            if (!$scheduledAt) {
                return $this->error('Invalid scheduled_at format. Use ISO 8601 format', 400, 'invalid_date_format');
            }
            $data['scheduled_at'] = $scheduledAt;
        }

        $reminder = ReminderManager::update((int) $id, $data, (int) $currentActor['id']);

        if (!$reminder) {
            return $this->error('Reminder not found or update failed', 404, 'not_found');
        }

        return $this->success($reminder, ['updated' => true]);
    }

    private function deleteReminder($id)
    {
        if (empty($id)) {
            return $this->error('Reminder ID is required', 400, 'missing_id');
        }

        $currentActor = CrmUserManager::getCurrentProfile();

        if (!$currentActor) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        $result = ReminderManager::delete((int) $id, (int) $currentActor['id']);

        if (!$result) {
            return $this->error('Reminder not found', 404, 'not_found');
        }

        return $this->success(['deleted' => true]);
    }

    private function parseDateTime(string $datetime): ?string
    {
        try {
            $dt = new \DateTime($datetime);
            $dt->setTimezone(new \DateTimeZone('UTC'));
            return $dt->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return null;
        }
    }
}
