<?php

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/auth.php';
$today = date('Y-m-d');

$stmt = $pdo->query("
SELECT e.name, e.email, d.*
FROM employee_docs d
JOIN employees e ON e.id = d.employee_id
");

while ($row = $stmt->fetch()) {

  $docs = [
    'الإقامة' => $row['visa_expiry'],
    'الهوية الإماراتية' => $row['emirates_id_expiry'],
    'التأمين الصحي' => $row['insurance_expiry'],
    'جواز السفر' => $row['passport_expiry']
  ];

  foreach ($docs as $doc_name => $expiry_date) {

    if (!$expiry_date) continue;

    $expiry = new DateTime($expiry_date);
    $now = new DateTime($today);

    $days_left = ($expiry->getTimestamp() - $now->getTimestamp()) / 86400;
    $days_left = floor($days_left);

    $notify_days = [30,15,7,3,0];

    if (in_array($days_left, $notify_days)) {

      if ($row['last_notified'] == $today) continue;

      $subject = "تنبيه: قرب انتهاء {$doc_name}";

      $message = "
      الموظف: {$row['name']}
      المستند: {$doc_name}
      تاريخ الانتهاء: {$expiry_date}
      الأيام المتبقية: {$days_left}
      ";

      $hr_email = "like.050.me@gmail.com";
mail($hr_email, $subject, $message);


      $update = $pdo->prepare("
        UPDATE employee_docs
        SET last_notified = ?
        WHERE id = ?
      ");
      $update->execute([$today, $row['id']]);
    }
  }
}
