<?php
declare(strict_types=1);
require_once __DIR__ . '/functions.php';

// Schema setup - only run when needed
function ensure_notifications_tables(PDO $pdo): void {
    static $done = false;
    if ($done) return;
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS notifications (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      user_id INTEGER NOT NULL,
      type TEXT NOT NULL,
      title TEXT,
      body TEXT,
      data_json TEXT,
      status TEXT NOT NULL DEFAULT 'unread',
      created_at TEXT NOT NULL,
      read_at TEXT
    )");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS notification_prefs (
      user_id INTEGER PRIMARY KEY,
      inapp_enabled INTEGER NOT NULL DEFAULT 1,
      email_enabled INTEGER NOT NULL DEFAULT 1,
      types_json TEXT
    )");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS email_queue (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      to_email TEXT NOT NULL,
      subject TEXT NOT NULL,
      template TEXT NOT NULL,
      payload_json TEXT,
      status TEXT NOT NULL DEFAULT 'queued',
      attempts INTEGER NOT NULL DEFAULT 0,
      last_error TEXT,
      created_at TEXT NOT NULL,
      sent_at TEXT
    )");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS email_verifications (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      user_id INTEGER NOT NULL,
      token TEXT NOT NULL UNIQUE,
      created_at TEXT NOT NULL,
      expires_at TEXT NOT NULL,
      verified_at TEXT
    )");
    
    try { $pdo->exec("ALTER TABLE users ADD COLUMN email_verified_at TEXT"); } catch (\Throwable $e) {}
    
    // Backward-compatible migrations
    ensure_column($pdo,'email_queue','created_at',"TEXT NOT NULL DEFAULT ''");
    ensure_column($pdo,'email_queue','to_email',"TEXT NOT NULL DEFAULT ''");
    ensure_column($pdo,'email_queue','subject',"TEXT NOT NULL DEFAULT ''");
    ensure_column($pdo,'email_queue','payload_json',"TEXT DEFAULT '{}'");
    ensure_column($pdo,'email_queue','sent_at','TEXT');
    ensure_column($pdo,'email_queue','attempts','INTEGER NOT NULL DEFAULT 0');
    ensure_column($pdo,'email_queue','status',"TEXT NOT NULL DEFAULT 'queued'");
    ensure_column($pdo,'email_queue','last_error','TEXT');
    
    $done = true;
}

function ensure_column(PDO $pdo, string $table, string $column, string $ddl): void {
  try {
    $cols = $pdo->query("PRAGMA table_info(\"{$table}\")")->fetchAll();
    $names = array_column($cols ?: [], 'name');
    if (!in_array($column, $names, true)) {
      $pdo->exec("ALTER TABLE \"{$table}\" ADD COLUMN \"{$column}\" {$ddl}");
    }
  } catch (\Throwable $e) { /* ignore */ }
}

function get_user_prefs(PDO $pdo, int $userId): array {
  ensure_notifications_tables($pdo);
  $q=$pdo->prepare("SELECT * FROM notification_prefs WHERE user_id=?"); $q->execute([$userId]); $r=$q->fetch();
  return $r ?: ['inapp_enabled'=>1,'email_enabled'=>1,'types_json'=>null];
}

function notify_inapp(PDO $pdo, int $userId, string $type, string $title, string $body, array $data=[]): void {
  ensure_notifications_tables($pdo);
  $p = get_user_prefs($pdo, $userId);
  if (!(int)($p['inapp_enabled'] ?? 1)) return;
  $stmt = $pdo->prepare("INSERT INTO notifications (user_id,type,title,body,data_json,status,created_at) VALUES (?,?,?,?,?,'unread',?)");
  $stmt->execute([$userId,$type,$title,$body,json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),date('c')]);
}

function queue_email(PDO $pdo, string $toEmail, string $subject, string $template, array $payload): void {
  ensure_notifications_tables($pdo);
  $stmt=$pdo->prepare("INSERT INTO email_queue (to_email,subject,template,payload_json,status,attempts,created_at) VALUES (?,?,?,?, 'queued',0,?)");
  $stmt->execute([$toEmail,$subject,$template,json_encode($payload,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),date('c')]);
}

function render_email_html(string $template, array $payload): string {
  $body = '';
  if ($template==='verification') {
    $body = "<h2>Verify your email</h2><p>Hello ".htmlspecialchars($payload['name'] ?? 'User').",</p><p>Please verify your email by clicking the link below:</p><p><a href=\"".htmlspecialchars($payload['link'])."\">Verify Email</a></p><p>If you did not create an account, please ignore this message.</p>";
  } elseif ($template==='app_update') {
    $body = "<h2>Application update</h2><p>".htmlspecialchars($payload['message'] ?? '')."</p><p><a href=\"".htmlspecialchars($payload['link'] ?? '/')."\">View application</a></p>";
  } elseif ($template==='chat') {
    $body = "<h2>New Message</h2><p>Hello ".htmlspecialchars($payload['name'] ?? 'User').",</p><p>".htmlspecialchars($payload['message'] ?? '')."</p><p><a href=\"".htmlspecialchars($payload['link'] ?? '/')."\">View Chat</a></p>";
  } else {
    $body = "<p>".htmlspecialchars($payload['message'] ?? '')."</p>";
  }
  // basic footer for GDPR
  $body .= "<hr><p style=\"font-size:12px;color:#64748b\">You are receiving this because you have a Go Legal account. Manage notification preferences in your account. Do not reply to this automated message.</p>";
  return "<!doctype html><html><body style=\"font-family:Arial,sans-serif;color:#0f172a\">{$body}</body></html>";
}

function process_email_queue(PDO $pdo, int $limit=10): array {
  require_once __DIR__ . '/settings.php';
  $smtpHost = get_setting($pdo, 'smtp_host');
  $smtpUser = get_setting($pdo, 'smtp_user');
  
  $rows = $pdo->prepare("SELECT * FROM email_queue WHERE status IN ('queued','retry') ORDER BY created_at ASC LIMIT ?");
  $rows->execute([$limit]); $list=$rows->fetchAll();
  $sent=0; $failed=0;
  foreach ($list as $m) {
    $id=(int)$m['id']; $attempts=(int)$m['attempts'];
    if ($attempts>=3) { $pdo->prepare("UPDATE email_queue SET status='failed', last_error=? WHERE id=?")->execute(['max attempts', $id]); $failed++; continue; }
    $html = render_email_html($m['template'], json_decode((string)$m['payload_json'], true) ?: []);
    
    // If SMTP is configured, we could use PHPMailer here. 
    // For "out of the box", we use PHP's mail() which works on most cPanels.
    $fromName = get_setting($pdo, 'sender_name', 'Go Legal');
    $fromEmail = get_setting($pdo, 'sender_email', 'noreply@golegal.ng');
    
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: {$fromName} <{$fromEmail}>\r\n";
    $headers .= "Reply-To: {$fromEmail}\r\n";
    $headers .= "Return-Path: {$fromEmail}\r\n";

    $ok = @mail($m['to_email'], $m['subject'], $html, $headers, "-f{$fromEmail}");
    if ($ok) {
      $pdo->prepare("UPDATE email_queue SET status='sent', sent_at=?, attempts=? WHERE id=?")->execute([date('c'), $attempts+1, $id]);
      $sent++;
    } else {
      $pdo->prepare("UPDATE email_queue SET status='retry', attempts=?, last_error=? WHERE id=?")->execute([$attempts+1, 'send failed', $id]);
      $failed++;
    }
  }
  return ['sent'=>$sent,'failed'=>$failed];
}

function send_verification_email(PDO $pdo, int $userId, string $email, string $name): void {
  $token = bin2hex(random_bytes(16));
  $pdo->prepare("INSERT INTO email_verifications (user_id, token, created_at, expires_at) VALUES (?,?,?,?)")
      ->execute([$userId,$token,date('c'),date('c', time()+86400)]);
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $link = $scheme.'://'.$host.'/verify.php?token='.$token;
  queue_email($pdo, $email, 'Verify your Go Legal email', 'verification', ['name'=>$name,'link'=>$link]);
}

function admin_notify_application_event(PDO $pdo, int $adminId, int $applicationId, string $event, string $message): void {
  $q=$pdo->prepare("SELECT user_id FROM applications WHERE id=?"); $q->execute([$applicationId]); $app=$q->fetch();
  if (!$app) return;
  $userId=(int)$app['user_id'];
  $user=$pdo->prepare("SELECT email, full_name FROM users WHERE id=?"); $user->execute([$userId]); $u=$user->fetch();
  // In-app
  notify_inapp($pdo, $userId, 'app_event', ucfirst($event), $message, ['application_id'=>$applicationId]);
  // Email if enabled
  $prefs = get_user_prefs($pdo, $userId);
  if ((int)($prefs['email_enabled'] ?? 1)) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $link = $scheme.'://'.$host.'/customer/view_application.php?id='.$applicationId;
    queue_email($pdo, (string)$u['email'], 'Application update', 'app_update', ['name'=>$u['full_name'] ?? '','message'=>$message,'link'=>$link]);
  }
  // Audit
  $stmt=$pdo->prepare("INSERT INTO audit_logs (actor_user_id,action,entity,entity_id,payload,ip,created_at) VALUES (?,?,?,?,?,?,?)");
  $stmt->execute([$adminId,'application.'.$event,'application',$applicationId,json_encode(['message'=>$message],JSON_UNESCAPED_UNICODE), $_SERVER['REMOTE_ADDR'] ?? '', date('c')]);
}

function mark_notification_read(PDO $pdo, int $userId, int $notifId): void {
  $pdo->prepare("UPDATE notifications SET status='read', read_at=? WHERE id=? AND user_id=?")->execute([date('c'), $notifId, $userId]);
}
