<?php
// Handle POST request for account deletion form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
require __DIR__ . '/phpmailer/PHPMailer.php';
require __DIR__ . '/phpmailer/SMTP.php';
require __DIR__ . '/phpmailer/Exception.php';
$env = require '/home/akgbilis/fi_sf/.env.php';



    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        $data = $_POST;
    }

    $email  = trim($data['email'] ?? '');
    $reason = trim($data['reason'] ?? '');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'error' => 'Invalid email']);
        exit;
    }

    $subject = 'BetsAI - Account Deletion Request';
    $message = "Account deletion request\nEmail: {$email}\nReason: {$reason}\nIP: " . ($_SERVER['REMOTE_ADDR'] ?? '') . "\nUA: " . ($_SERVER['HTTP_USER_AGENT'] ?? '');

    try {
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        $mail->CharSet = 'UTF-8';
        $mail->isSMTP();
        $mail->Host       = 'mail.akgbilisim.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'support-android@akgbilisim.com';
        $mail->Password   = $env['mail_password'] ?? '';
        $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; // 465/SSL
        $mail->Port       = 465;

        // Paylaşımlı hostinglerde sertifika uyarısı olursa (gerekirse aç)
        // $mail->SMTPOptions = [
        //   'ssl' => [
        //     'verify_peer' => false,
        //     'verify_peer_name' => false,
        //     'allow_self_signed' => true,
        //   ],
        // ];

        $mail->setFrom('support-android@akgbilisim.com', 'BetsAI Robot');
        $mail->addAddress('support-android@akgbilisim.com', 'Support');
        $mail->addReplyTo($email);

        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->AltBody = $message;

        // Debug için geçici olarak açılabilir (sonra kapat)
        // $mail->SMTPDebug = 2; // veya 3

        $ok = $mail->send();
        echo json_encode(['success' => (bool)$ok]);
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Mailer Error: ' . $e->getMessage()]);
    }
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>BetsAI – Account Deletion Request</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { font-family: sans-serif; max-width: 600px; margin: 40px auto; padding: 0 16px; line-height: 1.5 }
    h1 { font-size: 1.5rem }
    label { display:block; margin-top:12px }
    input, button { padding: 8px; margin-top: 6px; width: 100% }
  </style>
</head>
<body>
  <h1>Delete your BetsAI account</h1>
  <p>
    By submitting this form, you can request permanent deletion of your BetsAI account.  
    This will remove your profile, authentication record, credits and prediction history.  
    Server logs are retained up to 90 days for fraud prevention.
  </p>

  <form id="delForm" autocomplete="on" novalidate>
    <label for="email">Your account email (Google Sign-In):</label>
    <input type="email" name="email" id="email" required>

    <label for="reason">Reason for deletion (optional):</label>
    <textarea name="reason" id="reason" rows="3"></textarea>

    <button type="submit">Send Deletion Request</button>
    <div id="msg" style="margin-top:10px"></div>
  </form>

  <p>If you need help, contact us directly at <a href="mailto:gnncmhmtw@gmail.com">gnncmhmtw@gmail.com</a></p>

  <script>
    const form = document.getElementById('delForm');
    const msg  = document.getElementById('msg');
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      msg.textContent = 'Sending…';
      const payload = {
        email: document.getElementById('email').value.trim(),
        reason: document.getElementById('reason').value.trim()
      };
      try {
        const res = await fetch('delete_account_request.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        const data = await res.json().catch(()=>({}));
        if (res.ok && data.success) {
          msg.innerHTML = '<span class="ok">Your request has been received. We will contact you by email.</span>';
          form.reset();
        } else {
          msg.innerHTML = '<span class="err">Could not send your request. Please try again later.</span>';
        }
      } catch {
        msg.innerHTML = '<span class="err">Network error. Please try again.</span>';
      }
    });
  </script>
</body>
</html>