<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Libraries\StaffTimeOffLinkService;

class TimeOffNotificationController extends BaseController
{
    /**
     * Triggered when the principal clicks the confirmation link in the email.
     * Sends a courtesy notification to the staff member who submitted the request.
     */
    public function notify(string $token = '')
    {
        $service = new StaffTimeOffLinkService();
        $payload = $service->parseToken($token);

        if (!$payload) {
            return $this->respondHtml('Sorry, this link is invalid or has expired.', 400);
        }

        $email = trim((string)($payload['email'] ?? ''));
        $fullName = trim((string)($payload['name'] ?? ''));

        if ($email === '') {
            return $this->respondHtml('Unable to notify the requester because their email was not included.', 400);
        }

        $dates = (string)($payload['dates'] ?? '-');
        $role  = (string)($payload['role'] ?? 'staff');
        $reason = (string)($payload['reason'] ?? '');
        $reasonType = (string)($payload['reason_type'] ?? '');
        $submittedAt = (string)($payload['submitted_at'] ?? '');
        $origin = (string)($payload['origin'] ?? 'staff portal');

        try {
            $mailer = \Config\Services::emailService();
            $subject = 'TimeOff Request - Principal Acknowledgment';
            $body = '<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.5;">'
                  . '<p>Dear ' . esc($fullName ?: 'Staff Member') . ',</p>'
                  . '<p>This is a courtesy confirmation that your time-off request submitted via the '
                  . esc($origin) . ' has been reviewed by the principal.</p>'
                  . '<table cellpadding="6" cellspacing="0" style="border-collapse:collapse;">'
                  . '<tr><td><strong>Role</strong></td><td>' . esc($role) . '</td></tr>'
                  . '<tr><td><strong>Dates</strong></td><td>' . esc($dates ?: '-') . '</td></tr>'
                  . '<tr><td><strong>Reason Type</strong></td><td>' . esc($reasonType ?: '-') . '</td></tr>'
                  . '<tr><td><strong>Reason</strong></td><td>' . esc($reason ?: '-') . '</td></tr>'
                  . ($submittedAt !== '' ? '<tr><td><strong>Submitted At</strong></td><td>' . esc($submittedAt) . '</td></tr>' : '')
                  . '</table>'
                  . '<p>If you have any follow-up questions, please contact the principal\'s office directly.</p>'
                  . '<p style="margin-top:16px;">Thank you,<br>Al Rahma School Administration</p>'
                  . '</div>';

            $mailer->send($email, $subject, $body, 'notifications');
        } catch (\Throwable $e) {
            log_message('error', 'Failed to send TimeOff confirmation to requester: ' . $e->getMessage());
            return $this->respondHtml('Something went wrong while sending the confirmation email. Please contact IT for help.', 500);
        }

        return $this->respondHtml('Confirmation email sent to the requester. You may close this window.');
    }

    private function respondHtml(string $message, int $statusCode = 200)
    {
        $html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>TimeOff</title></head>'
              . '<body style="font-family:Arial,Helvetica,sans-serif;padding:24px;">'
              . '<p>' . esc($message) . '</p>'
              . '</body></html>';

        return $this->response
            ->setStatusCode($statusCode)
            ->setHeader('Content-Type', 'text/html; charset=UTF-8')
            ->setBody($html);
    }
}
