<?php
/**
 * OSCE Nexus — account-deletion request handler.
 *
 * Receives the POST from account-deletion.html, then:
 *   1. Appends the request to a protected log file (audit trail / tracking).
 *   2. Emails a ticket to the administrator.
 *   3. (Optional) Mirrors the email through Web3Forms for guaranteed delivery.
 *   4. Shows the requester a styled confirmation with a ticket reference.
 *
 * Drop this file in the same web folder as account-deletion.html.
 */

// ---------------------------------------------------------------------------
// CONFIG — edit these three values if needed.
// ---------------------------------------------------------------------------
$RECIPIENT     = 'ac@adresponder.site';                  // where tickets go
$MAIL_FROM     = 'noreply@osce.skmcsimcenter.cloud';     // must be on THIS domain
$WEB3FORMS_KEY = '';   // optional: paste a free key from web3forms.com for a
                       // delivery backup. Leave '' to rely on PHP mail() only.
// ---------------------------------------------------------------------------

// Optional SMTP. Create smtp-config.php next to this file (copy it from
// smtp-config.sample.php and fill in your mail server details). When present,
// the ticket is sent through your SMTP server instead of PHP mail(). Returns
// an array of settings, or false if the file isn't there yet.
$SMTP = @include __DIR__ . '/smtp-config.php';

// Only accept POST submissions; bounce anyone hitting the URL directly.
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    header('Location: account-deletion.html');
    exit;
}

// Spam honeypot: real browsers leave this empty. Pretend success and stop.
if (!empty($_POST['company'])) {
    render_confirmation('OSCE-DEL-IGNORED');
    exit;
}

// --- Collect & sanitise input ---------------------------------------------
function field($k, $max = 2000) {
    $v = isset($_POST[$k]) ? trim((string) $_POST[$k]) : '';
    $v = str_replace(["\r", "\0"], '', $v);          // strip CR / NUL
    return mb_substr($v, 0, $max);
}

$name     = field('name', 120);
$email    = field('email', 190);
$username = field('username', 120);
$facility = field('facility', 160);
$scope    = field('scope', 60);
$details  = field('details', 2000);
$confirm  = isset($_POST['confirm']) && $_POST['confirm'] === 'yes';

// --- Validate ---------------------------------------------------------------
$errors = [];
if ($name === '')                                     $errors[] = 'name is required';
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL))
                                                      $errors[] = 'a valid email is required';
if (!$confirm)                                        $errors[] = 'confirmation is required';

if ($errors) {
    render_error($errors);
    exit;
}

// --- Build the ticket -------------------------------------------------------
try {
    $rand = strtoupper(bin2hex(random_bytes(3)));     // 6 hex chars
} catch (Exception $e) {
    $rand = strtoupper(substr(md5(uniqid('', true)), 0, 6));
}
$ticket = 'OSCE-DEL-' . date('Ymd') . '-' . $rand;
$now    = date('c');
$ip     = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$ua     = mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 300);

$record = [
    'ticket'    => $ticket,
    'timestamp' => $now,
    'name'      => $name,
    'email'     => $email,
    'username'  => $username,
    'facility'  => $facility,
    'scope'     => $scope,
    'details'   => $details,
    'ip'        => $ip,
    'userAgent' => $ua,
];

// --- 1) Persist to a protected log folder (tracking / audit) ----------------
log_request($record);

// --- 2) Email the ticket to the administrator -------------------------------
$sent = false;
if (is_array($SMTP)) {
    $sent = send_via_smtp($SMTP, $RECIPIENT, $record);   // preferred: real SMTP
}
if (!$sent) {
    send_admin_email($RECIPIENT, $MAIL_FROM, $record);   // fallback: PHP mail()
}

// --- 3) Optional delivery backup via Web3Forms ------------------------------
if ($WEB3FORMS_KEY !== '') {
    mirror_to_web3forms($WEB3FORMS_KEY, $RECIPIENT, $record);
}

// --- 4) Confirm to the requester --------------------------------------------
render_confirmation($ticket);
exit;


// ===========================================================================
// Helpers
// ===========================================================================

/**
 * Append the request as one JSON line to a folder that is not web-readable.
 * On Apache the dropped .htaccess blocks direct download; on Nginx protect the
 * folder in your server config (see README).
 */
function log_request(array $record) {
    $dir = __DIR__ . '/deletion-requests';
    if (!is_dir($dir)) {
        @mkdir($dir, 0750, true);
    }
    // Belt-and-braces: deny web access to the log folder.
    $ht = $dir . '/.htaccess';
    if (!file_exists($ht)) {
        @file_put_contents($ht, "Require all denied\nDeny from all\n");
    }
    $idx = $dir . '/index.html';
    if (!file_exists($idx)) {
        @file_put_contents($idx, '');
    }
    $line = json_encode($record, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
    @file_put_contents($dir . '/requests.jsonl', $line, FILE_APPEND | LOCK_EX);
}

function build_email_body(array $r) {
    $body  = "A new account-deletion request was submitted.\n\n";
    $body .= "Ticket:    {$r['ticket']}\n";
    $body .= "Received:  {$r['timestamp']}\n";
    $body .= "----------------------------------------\n";
    $body .= "Name:      {$r['name']}\n";
    $body .= "Email:     {$r['email']}\n";
    $body .= "Username:  {$r['username']}\n";
    $body .= "Facility:  {$r['facility']}\n";
    $body .= "Scope:     {$r['scope']}\n";
    $body .= "Details:   {$r['details']}\n";
    $body .= "----------------------------------------\n";
    $body .= "IP:        {$r['ip']}\n";
    $body .= "UserAgent: {$r['userAgent']}\n\n";
    $body .= "Action within 30 days, then reply to the requester to confirm.\n";
    return $body;
}

/**
 * Send via a real SMTP server using PHPMailer. Returns true on success, false
 * if PHPMailer isn't installed or the send fails (the caller then falls back to
 * PHP mail()). See smtp-config.sample.php / README for setup.
 */
function send_via_smtp(array $cfg, $to, array $r) {
    if (!load_phpmailer()) {
        @error_log('OSCE deletion: PHPMailer not found; falling back to mail().');
        return false;
    }
    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = $cfg['host'];
        $mail->Port       = (int) $cfg['port'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $cfg['username'];
        $mail->Password   = $cfg['password'];
        $mail->SMTPSecure = (($cfg['secure'] ?? 'tls') === 'ssl')
            ? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS      // port 465
            : \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;  // port 587
        $mail->CharSet    = 'UTF-8';
        $mail->setFrom($cfg['from_email'], $cfg['from_name'] ?? 'OSCE Nexus');
        $mail->addAddress($to);
        if (filter_var($r['email'], FILTER_VALIDATE_EMAIL)) {
            $mail->addReplyTo($r['email'], $r['name']);
        }
        $mail->Subject = '[OSCE Nexus] Account deletion request ' . $r['ticket'];
        $mail->Body    = build_email_body($r);
        $mail->send();
        return true;
    } catch (\Throwable $e) {
        @error_log('OSCE deletion SMTP failed: ' . $e->getMessage());
        return false;
    }
}

/** Make the PHPMailer classes available, via composer or a manual drop-in. */
function load_phpmailer() {
    if (class_exists('\\PHPMailer\\PHPMailer\\PHPMailer')) {
        return true;
    }
    // composer install (vendor/)
    $autoload = __DIR__ . '/vendor/autoload.php';
    if (file_exists($autoload)) {
        require_once $autoload;
    }
    // manual: unzip PHPMailer into ./PHPMailer/ so PHPMailer/src/*.php exists
    $src = __DIR__ . '/PHPMailer/src/';
    foreach (['Exception.php', 'PHPMailer.php', 'SMTP.php'] as $f) {
        if (file_exists($src . $f)) {
            require_once $src . $f;
        }
    }
    return class_exists('\\PHPMailer\\PHPMailer\\PHPMailer');
}

function send_admin_email($to, $from, array $r) {
    $subject = '[OSCE Nexus] Account deletion request ' . $r['ticket'];
    $body    = build_email_body($r);

    // Encode the subject for non-ASCII safety; set a same-domain From so the
    // message is less likely to be flagged, and Reply-To the requester.
    $headers  = 'From: OSCE Nexus <' . $from . ">\r\n";
    $headers .= 'Reply-To: ' . $r['email'] . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $headers .= "X-Mailer: OSCE-Nexus\r\n";

    $encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';

    @mail($to, $encodedSubject, $body, $headers, '-f' . $from);
}

function mirror_to_web3forms($key, $to, array $r) {
    $payload = [
        'access_key' => $key,
        'subject'    => '[OSCE Nexus] Account deletion request ' . $r['ticket'],
        'from_name'  => 'OSCE Nexus Deletion Form',
        'email'      => $to,           // where web3forms delivers
        'replyto'    => $r['email'],
        'Ticket'     => $r['ticket'],
        'Name'       => $r['name'],
        'Account email' => $r['email'],
        'Username'   => $r['username'],
        'Facility'   => $r['facility'],
        'Scope'      => $r['scope'],
        'Details'    => $r['details'],
        'Received'   => $r['timestamp'],
    ];
    if (!function_exists('curl_init')) {
        return; // cURL not available; PHP mail() already attempted.
    }
    $ch = curl_init('https://api.web3forms.com/submit');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
    ]);
    @curl_exec($ch);
    @curl_close($ch);
}

function page_shell($title, $bodyHtml) {
    $css = <<<CSS
  :root { --brand:#2563eb; --ink:#1e293b; --muted:#64748b; --line:#e2e8f0; }
  * { box-sizing: border-box; }
  body { margin:0; font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
         color:var(--ink); line-height:1.65; background:#f7f8fa; }
  header { background:linear-gradient(135deg,#1e3a8a,#2563eb); color:#fff; padding:36px 20px; }
  .wrap { max-width:820px; margin:0 auto; padding:0 20px; }
  header .wrap { padding:0; }
  h1 { margin:0 0 6px; font-size:26px; }
  header p { margin:0; opacity:.9; }
  main { background:#fff; max-width:820px; margin:24px auto; padding:8px 28px 28px;
         border:1px solid var(--line); border-radius:14px; }
  h2 { color:var(--brand); font-size:18px; margin-top:28px; }
  .muted { color:var(--muted); font-size:14px; }
  a { color:var(--brand); }
  .ticket { display:inline-block; background:#eff6ff; border:1px solid #bfdbfe;
    border-radius:10px; padding:10px 16px; font-size:20px; font-weight:700;
    letter-spacing:.5px; color:#1d4ed8; margin:6px 0 4px; }
  .err { background:#fef2f2; border:1px solid #fecaca; color:#b91c1c;
    border-radius:10px; padding:12px 14px; }
  footer { text-align:center; color:var(--muted); font-size:13px; padding:24px; }
CSS;
    return "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
        . "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
        . "<title>{$title} — OSCE Nexus</title><style>{$css}</style></head><body>"
        . "<header><div class=\"wrap\"><h1>OSCE Nexus — Account &amp; Data Deletion</h1>"
        . "<p>Request received</p></div></header><main>{$bodyHtml}</main>"
        . "<footer>© 2026 Khalaf Almazrouei. OSCE Nexus™. All rights reserved.</footer>"
        . "</body></html>";
}

function render_confirmation($ticket) {
    $t = htmlspecialchars($ticket, ENT_QUOTES, 'UTF-8');
    $body = "<h2>Thank you — your request has been received</h2>"
        . "<p>Your account-deletion request has been logged and sent to our administrator.</p>"
        . "<p class=\"muted\">Your ticket reference:</p>"
        . "<div class=\"ticket\">{$t}</div>"
        . "<p>Please keep this reference for any follow-up. We will action your request "
        . "normally <strong>within 30 days</strong> and email you a confirmation once your "
        . "account has been deleted. We may first verify that the request comes from the "
        . "account holder.</p>"
        . "<p>Need to add something? Email "
        . "<a href=\"mailto:ac@adresponder.site?subject=OSCE%20Nexus%20deletion%20{$t}\">"
        . "ac@adresponder.site</a> quoting your ticket reference.</p>"
        . "<p><a href=\"account-deletion.html\">← Back</a></p>";
    echo page_shell('Request received', $body);
}

function render_error(array $errors) {
    http_response_code(400);
    $items = '';
    foreach ($errors as $e) {
        $items .= '<li>' . htmlspecialchars($e, ENT_QUOTES, 'UTF-8') . '</li>';
    }
    $body = "<h2>We couldn't submit your request</h2>"
        . "<div class=\"err\"><p>Please correct the following and try again:</p>"
        . "<ul>{$items}</ul></div>"
        . "<p><a href=\"account-deletion.html\">← Back to the form</a></p>";
    echo page_shell('Error', $body);
}
