<?php
declare(strict_types=1);
session_start();

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/inc/auth.php';

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';

use PHPMailer\PHPMailer\PHPMailer;

function out(array $a, int $code=200): void {
  http_response_code($code);
  echo json_encode($a, JSON_UNESCAPED_UNICODE);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') out(['ok'=>0,'msg'=>'Method not allowed'], 405);

if (empty($_SESSION['user_id'])) out(['ok'=>0,'msg'=>'انتهت الجلسة. سجّل دخول مرة أخرى.'], 401);

$role = strtoupper((string)($_SESSION['role'] ?? ''));
if ($role !== 'OWNER') out(['ok'=>0,'msg'=>'غير مصرح'], 403);

$csrf = (string)($_POST['csrf'] ?? '');
if ($csrf === '' || $csrf !== (string)($_SESSION['csrf'] ?? '')) out(['ok'=>0,'msg'=>'رمز الحماية غير صحيح'], 400);

$mode    = strtoupper((string)($_POST['mode'] ?? 'ALL'));
$scope   = strtoupper((string)($_POST['scope'] ?? 'BRANCH'));
$subject = trim((string)($_POST['subject'] ?? ''));
$body    = trim((string)($_POST['body'] ?? ''));

if (!in_array($mode, ['ALL','SELECTED'], true)) $mode = 'ALL';
if (!in_array($scope, ['BRANCH','ALL_BRANCHES'], true)) $scope = 'BRANCH';
if ($subject === '' || $body === '') out(['ok'=>0,'msg'=>'العنوان ونص الرسالة مطلوبان'], 422);

$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$branchId = (int)($_SESSION['branch_id'] ?? 1);

try {
  if ($mode === 'ALL') {
    $sql = "SELECT COALESCE(NULLIF(e.full_name,''), NULLIF(e.name,''), CONCAT('موظف #', e.id)) AS name,
                   u.email AS email
            FROM employees e
            LEFT JOIN users u ON u.id = e.user_id
            WHERE (u.email IS NOT NULL AND u.email <> '')";
    $params = [];
    if ($scope === 'BRANCH') {
      $sql .= " AND (e.branch_id IS NULL OR e.branch_id = :bid)";
      $params[':bid'] = $branchId;
    }
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $recipients = $st->fetchAll();
  } else {
    $empIds = $_POST['emp_ids'] ?? [];
    if (!is_array($empIds) || empty($empIds)) out(['ok'=>0,'msg'=>'اختر موظف واحد على الأقل'], 422);
    $empIds = array_values(array_unique(array_map('intval', $empIds)));
    $empIds = array_filter($empIds, fn($v)=>$v>0);
    if (empty($empIds)) out(['ok'=>0,'msg'=>'اختيار غير صالح'], 422);

    $in = implode(',', array_fill(0, count($empIds), '?'));
    $sql = "SELECT COALESCE(NULLIF(e.full_name,''), NULLIF(e.name,''), CONCAT('موظف #', e.id)) AS name,
                   u.email AS email
            FROM employees e
            LEFT JOIN users u ON u.id = e.user_id
            WHERE e.id IN ($in)
              AND (u.email IS NOT NULL AND u.email <> '')";
    if ($scope === 'BRANCH') { $sql .= " AND (e.branch_id IS NULL OR e.branch_id = ?)"; $empIds[] = $branchId; }

    $st = $pdo->prepare($sql);
    $st->execute($empIds);
    $recipients = $st->fetchAll();
  }
} catch (Throwable $e) {
  out(['ok'=>0,'msg'=>'خطأ في جلب المستلمين: '.$e->getMessage()], 500);
}

if (empty($recipients)) out(['ok'=>0,'msg'=>'لا يوجد مستلمين لديهم بريد صالح'], 422);

/* SMTP عدّل كلمة المرور */
const SMTP_HOST = 'mail.hamdanlegalgroup.ae';
const SMTP_PORT = 465;
const SMTP_USER = 'no-reply@hamdanlegalgroup.ae';
const SMTP_PASS = 'Saif1979s';
const SMTP_FROM = 'no-reply@hamdanlegalgroup.ae';
const FROM_NAME = 'HLG - HR';

$success = 0; $fail = 0; $errors = [];

foreach ($recipients as $r) {
  $toEmail = (string)($r['email'] ?? '');
  $toName  = (string)($r['name'] ?? '');
  if ($toEmail === '') { $fail++; continue; }

  $mail = new PHPMailer(true);
  try {
    $mail->CharSet = 'UTF-8';
    $mail->isSMTP();
    $mail->Host = SMTP_HOST;
    $mail->SMTPAuth = true;
    $mail->Username = SMTP_USER;
    $mail->Password = SMTP_PASS;
    $mail->Port = SMTP_PORT;
    $mail->SMTPSecure = (SMTP_PORT === 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;

    $mail->setFrom(SMTP_FROM, FROM_NAME);
    $mail->addAddress($toEmail, $toName);

    $mail->isHTML(true);
    $mail->Subject = $subject;

    $safeBody = nl2br(htmlspecialchars($body, ENT_QUOTES, 'UTF-8'));
    $mail->Body = "<div style='font-family:Tajawal,Arial;direction:rtl;text-align:right'>
      <div style='background:#0b6a7a;color:#fff;padding:12px;border-radius:12px 12px 0 0'>مجموعة حمدان القانونية</div>
      <div style='padding:14px;background:#ffffff;border-radius:0 0 12px 12px;color:#222'>
        <div style='white-space:pre-wrap;line-height:1.8'>{$safeBody}</div>
      </div>
    </div>";
    $mail->AltBody = $body;

    $mail->send();
    $success++;
  } catch (Throwable $e) {
    $fail++;
    $errors[] = $toEmail . " => " . $e->getMessage();
  }
}

out(['ok'=>1,'msg'=>"تم الإرسال. نجاح: {$success} ، فشل: {$fail}",'success'=>$success,'fail'=>$fail,'errors'=>$errors]);