<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) session_start();

header('Content-Type: application/json');

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}
include($config_path);

// Verify admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :uid");
$stmt->execute([':uid' => $_SESSION['user_id'] ?? 0]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

// Load SMTP config from DB
$smtp = get_mail_settings($pdo, $site_data);
if (empty($smtp['smtp_host']) || empty($smtp['smtp_username']) || empty($smtp['smtp_password'])) {
    echo json_encode(['status' => '0', 'msg' => 'SMTP is not configured. Go to Admin → Settings and fill in your SMTP details.']);
    exit();
}

$from_email = !empty($smtp['smtp_from_email']) ? $smtp['smtp_from_email'] : ($site_data['web_email'] ?? '');
$from_name  = !empty($smtp['smtp_from_name'])  ? $smtp['smtp_from_name']  : ($site_data['web_name'] ?? 'Website');

// Inputs
$recipient_type = trim($_POST['recipient_type'] ?? '');
$subject        = trim($_POST['subject'] ?? '');
$message        = trim($_POST['message'] ?? '');

if (empty($subject)) { echo json_encode(['status' => '0', 'msg' => 'Email subject is required']); exit(); }
if (empty($message)) { echo json_encode(['status' => '0', 'msg' => 'Email message is required']); exit(); }
if (!in_array($recipient_type, ['individual', 'all'])) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid recipient type']);
    exit();
}

// Fetch recipients
try {
    if ($recipient_type === 'all') {
        $stmt = $pdo->query("SELECT id, email, username, full_name FROM users WHERE status = 1");
        $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $user_ids = array_map('intval', $_POST['user_ids'] ?? []);
        if (empty($user_ids)) {
            echo json_encode(['status' => '0', 'msg' => 'Please select at least one recipient']);
            exit();
        }
        $ph   = implode(',', array_fill(0, count($user_ids), '?'));
        $stmt = $pdo->prepare("SELECT id, email, username, full_name FROM users WHERE id IN ($ph) AND status = 1");
        $stmt->execute($user_ids);
        $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    exit();
}

if (empty($recipients)) {
    echo json_encode(['status' => '0', 'msg' => 'No valid recipients found']);
    exit();
}

// ── Build email template ──────────────────────────────────────────────────────
$logo_url  = !empty($site_data['logo_url']) ? $site_data['logo_url'] : ($site_data['web_url'] . '/images/softbills.png');
$web_url   = $site_data['web_url']   ?? '';
$web_email = $site_data['web_email'] ?? '';
$year      = date('Y');

// WhatsApp number
$wa = '2349162671360';
if (!empty($site_data['whatsapp_number'])) {
    $wa = preg_replace('/[^0-9]/', '', $site_data['whatsapp_number']);
} elseif (!empty($site_data['support_url']) && strpos($site_data['support_url'], 'wa.me') !== false) {
    $wa = preg_replace('/[^0-9]/', '', $site_data['support_url']);
}
$wa_link       = 'https://wa.me/' . $wa;
$telegram_link = htmlspecialchars($site_data['channel_url'] ?? '#');

$email_body = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{$subject}</title>
</head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:'Segoe UI',Arial,sans-serif;">

<table width="100%" cellpadding="0" cellspacing="0" style="background:#f1f5f9;padding:30px 0;">
  <tr><td align="center">
    <table width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,0.08);">

      <!-- HEADER -->
      <tr>
        <td style="background:linear-gradient(135deg,#1a1a2e 0%,#16213e 50%,#0f3460 100%);padding:36px 40px;text-align:center;">
          <img src="{$logo_url}" alt="{$from_name}" style="max-height:52px;max-width:160px;margin-bottom:14px;display:block;margin-left:auto;margin-right:auto;">
          <h1 style="margin:0;font-size:22px;font-weight:700;color:#ffffff;letter-spacing:0.3px;">{$from_name}</h1>
          <p style="margin:6px 0 0;font-size:13px;color:rgba(255,255,255,0.6);letter-spacing:1px;text-transform:uppercase;">Official Communication</p>
        </td>
      </tr>

      <!-- SUBJECT BANNER -->
      <tr>
        <td style="background:#e8f0fe;padding:14px 40px;border-bottom:1px solid #d0deff;">
          <p style="margin:0;font-size:13px;color:#4a5568;font-weight:600;text-transform:uppercase;letter-spacing:0.8px;">&#128231; Message</p>
          <p style="margin:4px 0 0;font-size:17px;color:#1a202c;font-weight:700;">{$subject}</p>
        </td>
      </tr>

      <!-- BODY -->
      <tr>
        <td style="padding:36px 40px;color:#374151;font-size:15px;line-height:1.8;">
          {$message}
        </td>
      </tr>

      <!-- DIVIDER -->
      <tr>
        <td style="padding:0 40px;">
          <hr style="border:none;border-top:1px solid #e5e7eb;margin:0;">
        </td>
      </tr>

      <!-- CTA BUTTONS -->
      <tr>
        <td style="padding:30px 40px;text-align:center;background:#fafafa;">
          <p style="margin:0 0 18px;font-size:14px;color:#6b7280;font-weight:500;">Need help? Reach us instantly</p>
          <table cellpadding="0" cellspacing="0" style="margin:0 auto;">
            <tr>
              <td style="padding:0 6px;">
                <a href="{$wa_link}" target="_blank"
                   style="display:inline-block;background:#25D366;color:#ffffff;text-decoration:none;padding:12px 26px;border-radius:50px;font-size:14px;font-weight:700;letter-spacing:0.3px;">
                  &#128172; WhatsApp
                </a>
              </td>
              <td style="padding:0 6px;">
                <a href="{$telegram_link}" target="_blank"
                   style="display:inline-block;background:#0088cc;color:#ffffff;text-decoration:none;padding:12px 26px;border-radius:50px;font-size:14px;font-weight:700;letter-spacing:0.3px;">
                  &#9992; Telegram
                </a>
              </td>
            </tr>
          </table>
        </td>
      </tr>

      <!-- FOOTER -->
      <tr>
        <td style="background:#1a1a2e;padding:24px 40px;text-align:center;">
          <p style="margin:0 0 6px;font-size:13px;color:rgba(255,255,255,0.5);">
            <a href="{$web_url}" style="color:#7c9ef8;text-decoration:none;font-weight:600;">{$web_url}</a>
          </p>
          <p style="margin:0 0 10px;font-size:13px;color:rgba(255,255,255,0.5);">
            <a href="mailto:{$web_email}" style="color:#7c9ef8;text-decoration:none;">{$web_email}</a>
          </p>
          <p style="margin:0;font-size:11px;color:rgba(255,255,255,0.3);">
            &copy; {$year} {$from_name}. All rights reserved.<br>
            You received this email because you are a registered user.
          </p>
        </td>
      </tr>

    </table>
  </td></tr>
</table>

</body>
</html>
HTML;

// ── Send loop ─────────────────────────────────────────────────────────────────
$sent_count   = 0;
$failed_count = 0;
$first_error  = '';

foreach ($recipients as $recipient) {
    $to = $recipient['email'];
    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { $failed_count++; continue; }

    // Personalise greeting if message contains {{name}}
    $name           = !empty($recipient['full_name']) ? $recipient['full_name'] : $recipient['username'];
    $personal_body  = str_replace('{{name}}', htmlspecialchars($name), $email_body);

    try {
        $ok = send_system_email($to, $subject, $personal_body, $pdo, $site_data, [
            'from_email' => $from_email,
            'from_name'  => $from_name,
        ]);
        $ok ? $sent_count++ : ($failed_count++ + ($first_error ?: $first_error = "$to: send returned false"));
    } catch (Exception $e) {
        $failed_count++;
        if (!$first_error) $first_error = $to . ': ' . $e->getMessage();
    }

    if (count($recipients) > 10) usleep(150000);
}

if ($sent_count > 0) {
    $msg = "Email sent to <strong>{$sent_count}</strong> recipient(s).";
    if ($failed_count > 0) $msg .= " <small class='text-warning'>({$failed_count} failed)</small>";
    echo json_encode(['status' => '1', 'msg' => $msg, 'sent' => $sent_count, 'failed' => $failed_count]);
} else {
    $detail = $first_error ? '<br><small>' . htmlspecialchars($first_error) . '</small>' : '';
    echo json_encode(['status' => '0', 'msg' => 'Failed to send. Check your SMTP settings.' . $detail]);
}
