<?php
declare(strict_types=1);

// check_employee_docs.php
date_default_timezone_set('Asia/Dubai');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php';

/* ================== إعدادات عامة ================== */
$HR_EMAIL = 'lawyer.halkaabi@gmail.com';

$START_DAYS        = 30;   // يبدأ التنبيه قبل الانتهاء بـ 30 يوم
$STEP_DAYS         = 3;    // تكرار التنبيه كل 3 أيام داخل فترة القرب
$EXPIRED_EVERY_DAY = true; // المنتهي: يوميًا حتى يتم التحديث
$FROM_NAME         = 'HLG HR Bot';

/* رابط لوحة التحكم */
$ADMIN_KEY     = 'HLG-2026';
$DASHBOARD_URL = 'https://hlg.hamdanlegalgroup.ae/HLG-Justice-Hub/hr/hr_docs_dashboard.php?key=' . urlencode($ADMIN_KEY);

/* ================== إعدادات SMTP ================== */
$SMTP_HOST   = 'mail.hamdanlegalgroup.ae';
$SMTP_USER   = 'contact@hamdanlegalgroup.ae';
$SMTP_PASS   = 'Saif1979s';
$SMTP_PORT   = 587;
$SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS;

/* ================== إعدادات قاعدة البيانات ================== */
$DB_HOST = 'localhost';
$DB_NAME = 'hamdanle_hleg607';
$DB_USER = 'hamdanle_hleg607';
$DB_PASS = '@Saif1979s';

/* ================== دوال مساعدة ================== */
function h($s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function log_line(string $message): void
{
    file_put_contents(
        __DIR__ . '/cron_log.txt',
        date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL,
        FILE_APPEND
    );
}

function days_between(string $fromYmd, string $toYmd): int
{
    $from = new DateTime($fromYmd);
    $to   = new DateTime($toYmd);
    return (int)$from->diff($to)->format('%r%a');
}

function table_exists(PDO $pdo, string $table): bool
{
    static $cache = [];

    if (isset($cache[$table])) {
        return $cache[$table];
    }

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = :table
    ");
    $stmt->execute([':table' => $table]);

    $cache[$table] = ((int)$stmt->fetchColumn() > 0);
    return $cache[$table];
}

function column_exists(PDO $pdo, string $table, string $column): bool
{
    static $cache = [];

    $key = $table . '.' . $column;
    if (isset($cache[$key])) {
        return $cache[$key];
    }

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = :table
          AND COLUMN_NAME = :column
    ");
    $stmt->execute([
        ':table'  => $table,
        ':column' => $column,
    ]);

    $cache[$key] = ((int)$stmt->fetchColumn() > 0);
    return $cache[$key];
}

function delete_doc_alert(PDO $pdo, int $employeeId, int $docsId, string $docKey): void
{
    try {
        $stmt = $pdo->prepare("
            DELETE FROM hr_document_alerts
            WHERE employee_id = :employee_id
              AND docs_id = :docs_id
              AND document_key = :document_key
        ");
        $stmt->execute([
            ':employee_id'  => $employeeId,
            ':docs_id'      => $docsId,
            ':document_key' => $docKey,
        ]);

        log_line(
            'DELETE DONE => employee_id=' . $employeeId .
            ', docs_id=' . $docsId .
            ', key=' . $docKey
        );
    } catch (Throwable $e) {
        log_line(
            'Delete alert failed: employee_id=' . $employeeId .
            ', docs_id=' . $docsId .
            ', key=' . $docKey .
            ' | ' . $e->getMessage()
        );
    }
}

function upsert_doc_alert(
    PDO $pdo,
    int $employeeId,
    int $docsId,
    int $branchId,
    string $docKey,
    string $docLabel,
    string $expiry,
    int $daysLeft,
    bool $alertsHasBranchId,
    bool $alertsHasAlertType,
    bool $alertsHasIsRead,
    bool $alertsHasIsResolved,
    bool $alertsHasResolvedAt
): void {
    $statusValue = ($daysLeft < 0) ? 'expired' : 'warning';

    try {
        $checkStmt = $pdo->prepare("
            SELECT id
            FROM hr_document_alerts
            WHERE employee_id = :employee_id
              AND docs_id = :docs_id
              AND document_key = :document_key
            LIMIT 1
        ");
        $checkStmt->execute([
            ':employee_id'  => $employeeId,
            ':docs_id'      => $docsId,
            ':document_key' => $docKey,
        ]);

        $existsAlertId = $checkStmt->fetchColumn();

        if ($existsAlertId) {
            $parts = [
                'document_label = :document_label',
                'expiry_date = :expiry_date',
                'days_left = :days_left',
                'status = :status',
            ];

            if ($alertsHasBranchId) {
                $parts[] = 'branch_id = :branch_id';
            }
            if ($alertsHasIsRead) {
                $parts[] = 'is_read = 0';
            }
            if ($alertsHasIsResolved) {
                $parts[] = 'is_resolved = 0';
            }
            if ($alertsHasResolvedAt) {
                $parts[] = 'resolved_at = NULL';
            }

            $sql = "
                UPDATE hr_document_alerts
                SET " . implode(', ', $parts) . "
                WHERE id = :id
            ";

            $params = [
                ':document_label' => $docLabel,
                ':expiry_date'    => $expiry,
                ':days_left'      => $daysLeft,
                ':status'         => $statusValue,
                ':id'             => (int)$existsAlertId,
            ];

            if ($alertsHasBranchId) {
                $params[':branch_id'] = $branchId;
            }

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
        } else {
            $columns = [
                'employee_id',
                'docs_id',
                'document_key',
                'document_label',
                'expiry_date',
                'days_left',
                'status',
                'created_at',
            ];

            $values = [
                ':employee_id',
                ':docs_id',
                ':document_key',
                ':document_label',
                ':expiry_date',
                ':days_left',
                ':status',
                'NOW()',
            ];

            $params = [
                ':employee_id'    => $employeeId,
                ':docs_id'        => $docsId,
                ':document_key'   => $docKey,
                ':document_label' => $docLabel,
                ':expiry_date'    => $expiry,
                ':days_left'      => $daysLeft,
                ':status'         => $statusValue,
            ];

            if ($alertsHasBranchId) {
                $columns[] = 'branch_id';
                $values[]  = ':branch_id';
                $params[':branch_id'] = $branchId;
            }

            if ($alertsHasAlertType) {
                $columns[] = 'alert_type';
                $values[]  = ':alert_type';
                $params[':alert_type'] = 'document';
            }

            if ($alertsHasIsRead) {
                $columns[] = 'is_read';
                $values[]  = '0';
            }

            if ($alertsHasIsResolved) {
                $columns[] = 'is_resolved';
                $values[]  = '0';
            }

            $sql = "
                INSERT INTO hr_document_alerts
                (" . implode(', ', $columns) . ")
                VALUES
                (" . implode(', ', $values) . ")
            ";

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
        }
    } catch (Throwable $e) {
        log_line(
            'Upsert alert failed: employee_id=' . $employeeId .
            ', docs_id=' . $docsId .
            ', key=' . $docKey .
            ' | ' . $e->getMessage()
        );
    }
}

/* ================== اتصال قاعدة البيانات ================== */
try {
    $pdo = new PDO(
        "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4",
        $DB_USER,
        $DB_PASS,
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
        ]
    );
} catch (Throwable $e) {
    http_response_code(500);
    log_line('DB connection failed: ' . $e->getMessage());
    exit("DB connection failed\n");
}

$today = date('Y-m-d');

/* ================== التحقق من الجداول/الأعمدة ================== */
if (!table_exists($pdo, 'employee_docs') || !table_exists($pdo, 'employees')) {
    log_line('Missing required tables: employees or employee_docs');
    exit("Required tables not found\n");
}

$employeesHasBranchId = column_exists($pdo, 'employees', 'branch_id');
$employeesHasName     = column_exists($pdo, 'employees', 'name');

$docsHasVisaNotified  = column_exists($pdo, 'employee_docs', 'visa_notified');
$docsHasEidNotified   = column_exists($pdo, 'employee_docs', 'eid_notified');
$docsHasInsNotified   = column_exists($pdo, 'employee_docs', 'insurance_notified');
$docsHasPassNotified  = column_exists($pdo, 'employee_docs', 'passport_notified');

$hasAlertsTable       = table_exists($pdo, 'hr_document_alerts');
$alertsHasIsResolved  = $hasAlertsTable && column_exists($pdo, 'hr_document_alerts', 'is_resolved');
$alertsHasIsRead      = $hasAlertsTable && column_exists($pdo, 'hr_document_alerts', 'is_read');
$alertsHasAlertType   = $hasAlertsTable && column_exists($pdo, 'hr_document_alerts', 'alert_type');
$alertsHasResolvedAt  = $hasAlertsTable && column_exists($pdo, 'hr_document_alerts', 'resolved_at');
$alertsHasBranchId    = $hasAlertsTable && column_exists($pdo, 'hr_document_alerts', 'branch_id');

/* ================== جلب الموظفين + المستندات ================== */
$sql = "
SELECT
    e.id AS employee_id,
    " . ($employeesHasName ? "e.name" : "CONCAT('الموظف #', e.id)") . " AS employee_name,
    " . ($employeesHasBranchId ? "e.branch_id" : "0") . " AS branch_id,
    d.id AS docs_id,
    d.visa_expiry,
    d.emirates_id_expiry,
    d.insurance_expiry,
    d.passport_expiry,
    " . ($docsHasVisaNotified ? "d.visa_notified" : "NULL") . " AS visa_notified,
    " . ($docsHasEidNotified ? "d.eid_notified" : "NULL") . " AS eid_notified,
    " . ($docsHasInsNotified ? "d.insurance_notified" : "NULL") . " AS insurance_notified,
    " . ($docsHasPassNotified ? "d.passport_notified" : "NULL") . " AS passport_notified
FROM employee_docs d
JOIN employees e ON e.id = d.employee_id
";

$rows = $pdo->query($sql)->fetchAll();

/* ================== بناء التنبيهات + مزامنة جدول التنبيهات ================== */
$alerts = [];

foreach ($rows as $r) {
    $docsId     = (int)$r['docs_id'];
    $employeeId = (int)($r['employee_id'] ?? 0);
    $branchId   = (int)($r['branch_id'] ?? 0);
    $employee   = (string)($r['employee_name'] ?? 'بدون اسم');

    $docs = [
        [
            'key'          => 'visa',
            'label'        => 'الإقامة',
            'expiry'       => $r['visa_expiry'] ?? null,
            'notified_col' => 'visa_notified',
            'notified_val' => $r['visa_notified'] ?? null,
            'enabled'      => $docsHasVisaNotified,
        ],
        [
            'key'          => 'eid',
            'label'        => 'الهوية الإماراتية',
            'expiry'       => $r['emirates_id_expiry'] ?? null,
            'notified_col' => 'eid_notified',
            'notified_val' => $r['eid_notified'] ?? null,
            'enabled'      => $docsHasEidNotified,
        ],
        [
            'key'          => 'insurance',
            'label'        => 'التأمين الصحي',
            'expiry'       => $r['insurance_expiry'] ?? null,
            'notified_col' => 'insurance_notified',
            'notified_val' => $r['insurance_notified'] ?? null,
            'enabled'      => $docsHasInsNotified,
        ],
        [
            'key'          => 'passport',
            'label'        => 'جواز السفر',
            'expiry'       => $r['passport_expiry'] ?? null,
            'notified_col' => 'passport_notified',
            'notified_val' => $r['passport_notified'] ?? null,
            'enabled'      => $docsHasPassNotified,
        ],
    ];

    foreach ($docs as $doc) {
        $docKey   = (string)$doc['key'];
        $docLabel = (string)$doc['label'];
        $expiry   = trim((string)($doc['expiry'] ?? ''));

        if ($expiry === '' || $expiry === '0000-00-00') {
            if ($hasAlertsTable) {
                log_line(
                    'DELETE ALERT => employee_id=' . $employeeId .
                    ', docs_id=' . $docsId .
                    ', key=' . $docKey .
                    ', expiry=EMPTY'
                );
                delete_doc_alert($pdo, $employeeId, $docsId, $docKey);
            }
            continue;
        }

        $daysLeft = days_between($today, $expiry);

        log_line(
            'SCAN => employee_id=' . $employeeId .
            ', docs_id=' . $docsId .
            ', key=' . $docKey .
            ', expiry=' . $expiry .
            ', daysLeft=' . $daysLeft
        );

        if ($daysLeft > $START_DAYS) {
            if ($hasAlertsTable) {
                log_line(
                    'DELETE ALERT => employee_id=' . $employeeId .
                    ', docs_id=' . $docsId .
                    ', key=' . $docKey .
                    ', expiry=' . $expiry .
                    ', daysLeft=' . $daysLeft
                );
                delete_doc_alert($pdo, $employeeId, $docsId, $docKey);
            }
            continue;
        }

        $shouldNotify = false;

        if ($daysLeft >= 0 && $daysLeft <= $START_DAYS) {
            if (empty($doc['notified_val'])) {
                $shouldNotify = true;
            } else {
                $since = days_between((string)$doc['notified_val'], $today);
                if ($since >= $STEP_DAYS) {
                    $shouldNotify = true;
                }
            }
        }

        if ($daysLeft < 0) {
            if ($EXPIRED_EVERY_DAY) {
                $shouldNotify = true;
            } else {
                $since = empty($doc['notified_val']) ? 9999 : days_between((string)$doc['notified_val'], $today);
                if ($since >= $STEP_DAYS) {
                    $shouldNotify = true;
                }
            }
        }

        if (!$shouldNotify) {
            if ($hasAlertsTable) {
                upsert_doc_alert(
                    $pdo,
                    $employeeId,
                    $docsId,
                    $branchId,
                    $docKey,
                    $docLabel,
                    $expiry,
                    $daysLeft,
                    $alertsHasBranchId,
                    $alertsHasAlertType,
                    $alertsHasIsRead,
                    $alertsHasIsResolved,
                    $alertsHasResolvedAt
                );
            }
            continue;
        }

        if (!empty($doc['notified_val']) && (string)$doc['notified_val'] === $today) {
            continue;
        }

        $alerts[] = [
            'employee'     => $employee,
            'employee_id'  => $employeeId,
            'branch_id'    => $branchId,
            'document'     => $docLabel,
            'document_key' => $docKey,
            'expiry'       => $expiry,
            'days_left'    => $daysLeft,
            'status'       => ($daysLeft < 0) ? 'منتهي' : 'قريب الانتهاء',
            'docs_id'      => $docsId,
            'notified_col' => (string)$doc['notified_col'],
            'can_update'   => (bool)$doc['enabled'],
        ];
    }
}

/* ================== إذا لا توجد تنبيهات جديدة اليوم ================== */
if (count($alerts) === 0) {
    log_line('No alerts today (sync completed)');
    exit("No alerts today\n");
}

/* ================== ترتيب + إحصائيات ================== */
usort($alerts, static function ($a, $b) {
    $ad = (int)$a['days_left'];
    $bd = (int)$b['days_left'];

    if ($ad === $bd) {
        return 0;
    }

    return ($ad < $bd) ? -1 : 1;
});

$expiredCount = 0;
$nearCount    = 0;

foreach ($alerts as $a) {
    if ((int)$a['days_left'] < 0) {
        $expiredCount++;
    } else {
        $nearCount++;
    }
}

$subject = "تنبيهات وثائق الموظفين (HR) - {$today}";

/* ================== بناء Rows HTML ================== */
$rowsHtml = '';

foreach ($alerts as $a) {
    $dl = (int)$a['days_left'];
    $dlText = ($dl < 0) ? ('منتهي منذ ' . abs($dl) . ' يوم') : ('متبقي ' . $dl . ' يوم');

    if ($dl < 0) {
        $badgeBg = '#ffe1e1';
        $badgeTx = '#8a1f1f';
        $label   = 'منتهي';
    } else {
        $badgeBg = '#fff4d6';
        $badgeTx = '#8a5a00';
        $label   = 'قريب';
    }

    $rowsHtml .= '
    <tr>
        <td style="padding:12px;border-bottom:1px solid #eee;text-align:right;direction:rtl;">
            ' . h($a['employee']) . ' <span style="color:#8aa1a8;font-size:12px;">(ID: ' . (int)$a['employee_id'] . ')</span>
        </td>
        <td style="padding:12px;border-bottom:1px solid #eee;text-align:right;direction:rtl;">' . h($a['document']) . '</td>
        <td style="padding:12px;border-bottom:1px solid #eee;text-align:right;direction:rtl;">' . h($a['expiry']) . '</td>
        <td style="padding:12px;border-bottom:1px solid #eee;text-align:right;direction:rtl;">
            <span style="padding:6px 12px;border-radius:999px;font-size:12px;background:' . $badgeBg . ';color:' . $badgeTx . ';font-weight:700;display:inline-block;">' . $label . '</span>
            <span style="font-size:12px;color:#666;margin-right:8px;display:inline-block;">(' . h($dlText) . ')</span>
        </td>
    </tr>';
}

/* ================== HTML Body ================== */
$htmlBody = '
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body style="margin:0;background:#f3f6f8;font-family:Tajawal,Arial,sans-serif;direction:rtl;text-align:right;">
    <div style="max-width:850px;margin:20px auto;padding:10px;">

        <div style="background:linear-gradient(135deg,#00424f,#006a7a);color:#fff;border-radius:18px;padding:18px;text-align:right;">
            <div style="font-size:20px;font-weight:800;line-height:1.4;">تنبيهات وثائق الموظفين (HR)</div>
            <div style="font-size:13px;margin-top:6px;opacity:.9;">التاريخ: ' . h($today) . '</div>

            <div style="margin-top:12px;">
                <a href="' . h($DASHBOARD_URL) . '"
                   style="display:inline-block;background:#ffffff;color:#00424f;text-decoration:none;padding:10px 14px;border-radius:12px;font-weight:700;font-size:13px;">
                    فتح لوحة التحكم
                </a>
            </div>
        </div>

        <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:12px;direction:rtl;text-align:right;">
            <tr>
                <td style="width:33%;padding:6px;">
                    <div style="background:#fff;border-radius:14px;padding:14px;border:1px solid #e6eef0;">
                        <div style="font-size:12px;color:#777;">عدد التنبيهات</div>
                        <div style="font-size:22px;font-weight:800;">' . count($alerts) . '</div>
                    </div>
                </td>

                <td style="width:33%;padding:6px;">
                    <div style="background:#fff;border-radius:14px;padding:14px;border:1px solid #e6eef0;">
                        <div style="font-size:12px;color:#777;">منتهي</div>
                        <div style="font-size:22px;font-weight:800;color:#d62828;">' . (int)$expiredCount . '</div>
                    </div>
                </td>

                <td style="width:33%;padding:6px;">
                    <div style="background:#fff;border-radius:14px;padding:14px;border:1px solid #e6eef0;">
                        <div style="font-size:12px;color:#777;">قريب (≤ 30 يوم)</div>
                        <div style="font-size:22px;font-weight:800;color:#b08900;">' . (int)$nearCount . '</div>
                    </div>
                </td>
            </tr>
        </table>

        <div style="background:#fff;border-radius:16px;margin-top:14px;border:1px solid #e6eef0;overflow:hidden;">
            <div style="padding:14px;font-weight:800;border-bottom:1px solid #eee;text-align:right;">التفاصيل</div>

            <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;text-align:right;direction:rtl;">
                <thead>
                    <tr style="background:#f7fafb;font-size:13px;color:#555;">
                        <th style="padding:12px;text-align:right;">الموظف</th>
                        <th style="padding:12px;text-align:right;">المستند</th>
                        <th style="padding:12px;text-align:right;">تاريخ الانتهاء</th>
                        <th style="padding:12px;text-align:right;">الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    ' . $rowsHtml . '
                </tbody>
            </table>
        </div>

        <div style="text-align:center;color:#888;font-size:12px;margin-top:12px;">
            هذه رسالة آلية من نظام الموارد البشرية - مجموعة حمدان القانونية
        </div>

    </div>
</body>
</html>
';

/* ================== Plain Body ================== */
$plainLines   = [];
$plainLines[] = "تنبيهات وثائق الموظفين (HR)";
$plainLines[] = "التاريخ: {$today}";
$plainLines[] = "فتح لوحة التحكم: {$DASHBOARD_URL}";
$plainLines[] = "---------------------------";

foreach ($alerts as $a) {
    $dl = (int)$a['days_left'];
    $dlText = ($dl < 0) ? ('منتهي منذ ' . abs($dl) . ' يوم') : ('متبقي ' . $dl . ' يوم');

    $plainLines[] = "الموظف: {$a['employee']} (ID: {$a['employee_id']})";
    $plainLines[] = "المستند: {$a['document']}";
    $plainLines[] = "تاريخ الانتهاء: {$a['expiry']}";
    $plainLines[] = "الحالة: {$a['status']} ({$dlText})";
    $plainLines[] = "---------------------------";
}

$plainBody = implode("\n", $plainLines);

/* ================== إرسال البريد ================== */
$sent = false;
$errorMessage = '';

try {
    $mail = new PHPMailer(true);
    $mail->CharSet = 'UTF-8';

    $mail->isSMTP();
    $mail->Host       = $SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = $SMTP_USER;
    $mail->Password   = $SMTP_PASS;
    $mail->SMTPSecure = $SMTP_SECURE;
    $mail->Port       = $SMTP_PORT;

    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer'       => false,
            'verify_peer_name'  => false,
            'allow_self_signed' => true,
        ],
    ];

    $mail->setFrom($SMTP_USER, $FROM_NAME);
    $mail->addAddress($HR_EMAIL);

    $mail->Subject = $subject;
    $mail->isHTML(true);
    $mail->Body    = $htmlBody;
    $mail->AltBody = $plainBody;

    $mail->send();
    $sent = true;
} catch (Throwable $e) {
    $errorMessage = $e->getMessage();
    $sent = false;
}

/* ================== تحديث أعمدة notified + تسجيل التنبيهات ================== */
if ($sent) {
    $allowedCols = ['visa_notified', 'eid_notified', 'insurance_notified', 'passport_notified'];

    foreach ($alerts as $a) {
        if ($a['can_update'] && in_array($a['notified_col'], $allowedCols, true)) {
            try {
                $sqlUpd = "UPDATE employee_docs SET {$a['notified_col']} = :today WHERE id = :id";
                $stmtUpd = $pdo->prepare($sqlUpd);
                $stmtUpd->execute([
                    ':today' => $today,
                    ':id'    => (int)$a['docs_id'],
                ]);
            } catch (Throwable $e) {
                log_line(
                    'Failed updating notified column for docs_id=' .
                    (int)$a['docs_id'] . ': ' . $e->getMessage()
                );
            }
        }

        if ($hasAlertsTable) {
            upsert_doc_alert(
                $pdo,
                (int)$a['employee_id'],
                (int)$a['docs_id'],
                (int)$a['branch_id'],
                (string)$a['document_key'],
                (string)$a['document'],
                (string)$a['expiry'],
                (int)$a['days_left'],
                $alertsHasBranchId,
                $alertsHasAlertType,
                $alertsHasIsRead,
                $alertsHasIsResolved,
                $alertsHasResolvedAt
            );

            log_line(
                'Alert synced: employee_id=' . (int)$a['employee_id'] .
                ', docs_id=' . (int)$a['docs_id'] .
                ', key=' . (string)$a['document_key'] .
                ', expiry=' . (string)$a['expiry'] .
                ', days_left=' . (int)$a['days_left']
            );
        }
    }

    log_line('Sent to HR: ' . count($alerts) . ' alerts');
    echo "Sent to HR: " . count($alerts) . " alerts\n";
} else {
    log_line('Mail failed: ' . $errorMessage);
    echo "SMTP Mail failed: " . h($errorMessage) . "\n";
}