<?php
// ============================================================
//  mailer.php — PHPMailer wrapper
//  Install: composer require phpmailer/phpmailer
// ============================================================
require_once __DIR__ . '/config.php';

if (file_exists(__DIR__ . '/vendor/autoload.php'))
    require_once __DIR__ . '/vendor/autoload.php';
else {
    require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
    require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';
    require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailEx;

function sendMail(string $to, string $name, string $subject, string $html): bool {
    $m = new PHPMailer(true);
    try {
        $m->isSMTP();
        $m->Host       = SMTP_HOST;
        $m->SMTPAuth   = true;
        $m->Username   = SMTP_USER;
        $m->Password   = SMTP_PASS;
        if ((int)SMTP_PORT === 465) {
            $m->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $m->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }
        $m->Port       = SMTP_PORT;
        $m->Timeout    = 15; // fail fast (15 seconds) instead of hanging for 5 mins
        $m->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        $m->CharSet    = 'UTF-8';
        $m->setFrom(SMTP_FROM, SMTP_FROM_NAME);
        $m->addAddress($to, $name);
        $m->isHTML(true);
        $m->Subject = $subject;
        $m->Body    = $html;
        $m->AltBody = strip_tags(str_replace(['<br>','<br/>','</p>'], "\n", $html));
        $m->send();
        return true;
    } catch (MailEx $e) {
        error_log('PHPMailer: ' . $m->ErrorInfo);
        return false;
    }
}

function mailPasswordReset(string $to, string $name, string $link): bool {
    $html = <<<HTML
<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;background:#070e17;font-family:'Segoe UI',Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr><td align="center" style="padding:40px 20px;">
<table width="520" style="background:#132338;border-radius:20px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.5);">
  <tr><td style="background:linear-gradient(135deg,#1a3a5c,#c85a00);padding:30px;text-align:center;">
    <div style="font-size:2.2rem;">🛡️</div>
    <h1 style="color:#fff;font-size:1.2rem;margin:8px 0 4px;font-weight:700;">Hammerhead Protection Inc.</h1>
    <p style="color:rgba(255,255,255,.7);font-size:.82rem;margin:0;">Staff &amp; Site Manager</p>
  </td></tr>
  <tr><td style="padding:32px 36px;">
    <h2 style="color:#e2e8f0;font-size:1rem;margin:0 0 12px;">Password Reset Request</h2>
    <p style="color:#94a3b8;font-size:.88rem;line-height:1.7;margin:0 0 24px;">
      Hi <strong style="color:#e2e8f0;">$name</strong>, we received a request to reset your
      dashboard password. Click the button below — this link expires in
      <strong style="color:#f97316;">30 minutes</strong>.
    </p>
    <div style="text-align:center;margin:28px 0;">
      <a href="$link"
         style="background:linear-gradient(135deg,#c85a00,#f97316);color:#fff;
                padding:14px 36px;border-radius:50px;text-decoration:none;
                font-weight:700;font-size:.92rem;display:inline-block;
                box-shadow:0 6px 20px rgba(200,90,0,.5);">
        🔑 Reset My Password
      </a>
    </div>
    <p style="color:#64748b;font-size:.75rem;text-align:center;margin:0;">
      If you did not request this, ignore this email safely.
    </p>
  </td></tr>
  <tr><td style="background:#0d1b2a;padding:16px;text-align:center;">
    <p style="color:#334155;font-size:.7rem;margin:0;">© Hammerhead Protection Inc. · Authorized Personnel Only</p>
  </td></tr>
</table>
</td></tr>
</table>
</body></html>
HTML;
    return sendMail($to, $name, 'Password Reset — HHP Dashboard', $html);
}

// ── Task email builder ────────────────────────────────────────
// Shared HTML wrapper used by both task emails
function _taskEmailWrapper(string $headerTitle, string $headerSub, string $headerColor, string $body): string {
    return <<<HTML
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#070e17;font-family:'Segoe UI',Arial,Helvetica,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#070e17;">
<tr><td align="center" style="padding:36px 16px;">

<table width="560" cellpadding="0" cellspacing="0" style="max-width:560px;width:100%;background:#132338;border-radius:20px;overflow:hidden;box-shadow:0 12px 48px rgba(0,0,0,.6);">

  <!-- Header -->
  <tr><td style="background:$headerColor;padding:28px 32px;text-align:center;">
    <div style="font-size:2rem;margin-bottom:8px;">🛡️</div>
    <h1 style="color:#fff;font-size:1.1rem;font-weight:700;margin:0 0 4px;letter-spacing:.3px;">Hammerhead Protection Inc.</h1>
    <p  style="color:rgba(255,255,255,.75);font-size:.78rem;margin:0;">$headerSub</p>
    <div style="margin-top:14px;display:inline-block;background:rgba(0,0,0,.25);border-radius:20px;padding:5px 18px;">
      <span style="color:#fff;font-size:.85rem;font-weight:700;">$headerTitle</span>
    </div>
  </td></tr>

  <!-- Body -->
  <tr><td style="padding:30px 32px;">
    $body
  </td></tr>

  <!-- Footer -->
  <tr><td style="background:#0d1b2a;padding:16px 32px;text-align:center;border-top:1px solid rgba(255,255,255,.06);">
    <p style="color:#334155;font-size:.7rem;margin:0;">
      © Hammerhead Protection Inc. · This is an automated notification — do not reply.
    </p>
  </td></tr>

</table>
</td></tr>
</table>
</body></html>
HTML;
}

// Shared task detail rows
function _taskRows(array $rows): string {
    $html = '<table width="100%" cellpadding="0" cellspacing="0" style="margin:18px 0;border-radius:12px;overflow:hidden;border:1px solid rgba(255,255,255,.07);">';
    foreach ($rows as $label => $value) {
        if ($value === '' || $value === null) continue;
        $html .= '<tr>
            <td style="background:#0f1e2e;padding:10px 16px;font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#64748b;white-space:nowrap;width:38%;">' . htmlspecialchars($label) . '</td>
            <td style="background:#0d1b2a;padding:10px 16px;font-size:.84rem;color:#cbd5e0;border-left:1px solid rgba(255,255,255,.05);">' . htmlspecialchars((string)$value) . '</td>
        </tr>';
    }
    $html .= '</table>';
    return $html;
}

/**
 * Send notification to ASSIGNEE when a new task is created.
 *
 * @param array $t  The full task array from the createTask payload
 */
function mailTaskAssigned(array $t): bool {
    $to    = $t['mgrToEmail'] ?? '';
    $toName = $t['mgrTo']    ?? 'Manager';
    $concern = $t['concern'] === 'Others' && !empty($t['otherProcessType'])
               ? 'Others — ' . $t['otherProcessType']
               : ($t['concern'] ?? '');

    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) return false;

    $rows = _taskRows([
        'Task ID'            => $t['id']          ?? '',
        'Subject / Employee' => $t['subj']         ?? '',
        'Process Type'       => $concern,
        'Findings / Notes'   => $t['findings']     ?? '',
        'Date'               => $t['date']          ?? '',
        'Assigned By'        => $t['mgrBy']         ?? '',
        'Priority'           => strtoupper($t['startDate'] ?? ''),
        'Due Date'           => $t['endDate']       ?? '',
        'Status'             => $t['status']        ?? 'Pending',
        'Follow-up Required' => $t['followupRequired'] ?? 'No',
    ]);

    $assignedBy = htmlspecialchars($t['mgrBy'] ?? 'A manager');
    $subjectLine = htmlspecialchars($t['subj'] ?? 'a new task');

    $body = <<<HTML
<p style="color:#e2e8f0;font-size:.95rem;margin:0 0 6px;">Hi <strong>{$toName}</strong>,</p>
<p style="color:#94a3b8;font-size:.86rem;line-height:1.7;margin:6px 0 4px;">
  <strong style="color:#fdba74;">{$assignedBy}</strong> has assigned you a new task.
  Please review the details below and take necessary action.
</p>

{$rows}

<div style="text-align:center;margin:24px 0 8px;">
  <a href="{BASE_URL}/index.php"
     style="background:linear-gradient(135deg,#c85a00,#f97316);color:#fff;
            padding:13px 32px;border-radius:50px;text-decoration:none;
            font-weight:700;font-size:.88rem;display:inline-block;
            box-shadow:0 6px 20px rgba(200,90,0,.45);">
    📋 View Task in Dashboard
  </a>
</div>

<p style="color:#475569;font-size:.76rem;text-align:center;margin:10px 0 0;">
  Log in to the HHP Staff &amp; Site Manager portal to update status or add notes.
</p>
HTML;

    $body = str_replace('{BASE_URL}', BASE_URL, $body);

    $html = _taskEmailWrapper(
        'New Task Assigned',
        'Staff &amp; Site Manager — Task Notification',
        'linear-gradient(135deg,#1a3a5c 0%,#c85a00 100%)',
        $body
    );

    return sendMail($to, $toName, "📋 New Task Assigned — {$subjectLine}", $html);
}

/**
 * Send notification to NEW ASSIGNEE when a task is transferred.
 *
 * @param array  $task  Full task row from DB (already updated)
 * @param string $from  Name of previous assignee
 * @param string $note  Transfer note if any
 */
function mailTaskTransferred(array $task, string $from, string $note = ''): bool {
    $to     = $task['transferEmail'] ?? '';
    $toName = $task['transferTo']    ?? 'Manager';
    $concern = $task['concern'] === 'Others' && !empty($task['otherProcessType'])
               ? 'Others — ' . $task['otherProcessType']
               : ($task['concern'] ?? '');

    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) return false;

    $rows = _taskRows([
        'Task ID'            => $task['id']          ?? '',
        'Subject / Employee' => $task['subj']         ?? '',
        'Process Type'       => $concern,
        'Transferred From'   => $from,
        'Follow-Up Type'     => $task['followUp']     ?? '',
        'Follow-Up Date'     => $task['followUpDate'] ?? '',
        'Current Status'     => $task['status']       ?? 'Pending',
        'Transfer Note'      => $note,
    ]);

    $fromSafe  = htmlspecialchars($from  ?: 'A manager');
    $subjSafe  = htmlspecialchars($task['subj'] ?? 'a task');

    $body = <<<HTML
<p style="color:#e2e8f0;font-size:.95rem;margin:0 0 6px;">Hi <strong>{$toName}</strong>,</p>
<p style="color:#94a3b8;font-size:.86rem;line-height:1.7;margin:6px 0 4px;">
  A task has been <strong style="color:#fdba74;">transferred to you</strong> by
  <strong style="color:#fdba74;">{$fromSafe}</strong>. Please review the details and
  follow up as required.
</p>

{$rows}

<div style="text-align:center;margin:24px 0 8px;">
  <a href="{BASE_URL}/index.php"
     style="background:linear-gradient(135deg,#1a3a5c,#2e75b6);color:#fff;
            padding:13px 32px;border-radius:50px;text-decoration:none;
            font-weight:700;font-size:.88rem;display:inline-block;
            box-shadow:0 6px 20px rgba(30,73,118,.5);">
    ⇄ View Task in Dashboard
  </a>
</div>

<p style="color:#475569;font-size:.76rem;text-align:center;margin:10px 0 0;">
  Log in to the HHP Staff &amp; Site Manager portal to update status or add notes.
</p>
HTML;

    $body = str_replace('{BASE_URL}', BASE_URL, $body);

    $html = _taskEmailWrapper(
        'Task Transferred To You',
        'Staff &amp; Site Manager — Transfer Notification',
        'linear-gradient(135deg,#1a3a5c 0%,#1e4976 100%)',
        $body
    );

    return sendMail($to, $toName, "⇄ Task Transferred — {$subjSafe}", $html);
}
/**
 * Send notification to the logged-in MANAGER when they complete an action.
 */
function mailManagerAction(string $managerEmail, string $managerName, string $actionType, array $task, string $details): bool {
    $subj = $task['subj'] ?? 'N/A';
    $taskId = $task['id'] ?? 'N/A';

    $rows = _taskRows([
        'Task ID'     => $taskId,
        'Subject'     => $subj,
        'Action'      => $actionType,
        'Details'     => $details,
        'Date & Time' => date('Y-m-d H:i:s')
    ]);

    $body = <<<HTML
<p style="color:#e2e8f0;font-size:.95rem;margin:0 0 6px;">Hi <strong>{$managerName}</strong>,</p>
<p style="color:#94a3b8;font-size:.86rem;line-height:1.7;margin:6px 0 4px;">
  This is a notification to confirm that you have successfully completed an action:
  <strong style="color:#fdba74;">{$actionType}</strong>.
</p>

{$rows}

<div style="text-align:center;margin:24px 0 8px;">
  <a href="{BASE_URL}/index.php"
     style="background:linear-gradient(135deg,#0e5e9e,#1678c7,#26a0f5);color:#fff;
            padding:13px 32px;border-radius:50px;text-decoration:none;
            font-weight:700;font-size:.88rem;display:inline-block;
            box-shadow:0 6px 20px rgba(22,120,214,.3);">
    📋 Go to Dashboard
  </a>
</div>
HTML;

    $body = str_replace('{BASE_URL}', BASE_URL, $body);

    $html = _taskEmailWrapper(
        'Dashboard Action Notification',
        'Staff &amp; Site Manager — Action Log',
        'linear-gradient(135deg,#061b33 0%,#0d3b68 50%,#1268a7 100%)',
        $body
    );

    return sendMail($managerEmail, $managerName, "🔔 Action Completed: {$actionType} — Task #{$taskId}", $html);
}
