<?php
declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/* -----------------------------------------------------------
 |  1.  Session (stored outside public root for security)
 * ---------------------------------------------------------- */
$sessionDir = __DIR__ . '/../storage/sessions';
if (!is_dir($sessionDir)) {
    mkdir($sessionDir, 0700, true);
}
session_save_path($sessionDir);
session_start();

/* -----------------------------------------------------------
 |  2.  Composer autoloader
 * ---------------------------------------------------------- */
require dirname(__DIR__) . '/vendor/autoload.php';

/* -----------------------------------------------------------
 |  3.  Core constants  — adjust only here
 * ---------------------------------------------------------- */
const SMTP_USER     = 'info@researchpublicationsexperts.com';
const SMTP_APP_PWD  = 'zklcwixuobwcigpt';        // ← 16-char Gmail app-password, NO SPACES
const INTERNAL_MAIL = SMTP_USER;
const APP_NAME      = 'Research Publications Experts';
const LOG_FILE      = __DIR__ . '/php-error.log';

/* -----------------------------------------------------------
 |  4.  Basic logging
 * ---------------------------------------------------------- */
if (!is_dir(dirname(LOG_FILE))) {
    mkdir(dirname(LOG_FILE), 0777, true);
}
ini_set('log_errors', '1');
ini_set('error_log', LOG_FILE);

function logError(string $msg): void
{
    error_log(date('[Y-m-d H:i:s] ') . $msg . PHP_EOL, 3, LOG_FILE);
}

set_error_handler(function ($errno, $errstr, $file, $line) {
    if (!(error_reporting() & $errno)) {
        return false;
    }
    logError("PHP {$errno}: {$errstr} in {$file}:{$line}");
    return false;
});

/* -----------------------------------------------------------
 |  5.  Optional .env loader (quotes are stripped)
 * ---------------------------------------------------------- */
$envFile = __DIR__ . '/.env';
if (is_readable($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        if (str_starts_with(trim($line), '#')) {
            continue;
        }
        [$k, $v] = array_map('trim', explode('=', $line, 2));
        $v = trim($v, "\"'");                  // remove " or ' around the value
        if ($k !== '') {
            putenv("$k=$v");
        }
    }
}

/* -----------------------------------------------------------
 |  6.  Helper functions
 * ---------------------------------------------------------- */
function getUserIP(): string
{
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // can be “ip1, ip2, ip3…”
        return trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

function getIPInfo(string $ip): array
{
    $json = @file_get_contents("https://ipinfo.io/{$ip}/json");
    if ($json === false) {
        logError("IP lookup failed for {$ip}");
        return [];
    }
    return json_decode($json, true) ?: [];
}

function redirect(string $url, string $flash = ''): never
{
    if ($flash !== '') {
        $_SESSION['message'] = $flash;
    }
    header("Location: {$url}");
    exit;
}

/* -----------------------------------------------------------
 |  7.  Visitor metadata
 * ---------------------------------------------------------- */
$ip       = getUserIP();
$ipInfo   = getIPInfo($ip);
$city     = $ipInfo['city']    ?? 'N/A';
$region   = $ipInfo['region']  ?? 'N/A';
$country  = $ipInfo['country'] ?? 'N/A';
$loc      = $ipInfo['loc']     ?? 'N/A';
$org      = $ipInfo['org']     ?? 'N/A';
$referrer = $_SERVER['HTTP_REFERER'] ?? 'Direct / Unknown';

/* -----------------------------------------------------------
 |  8.  Form handler
 * ---------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send'])) {

    $name     = trim($_POST['name']      ?? '');
    $email    = trim($_POST['email']     ?? '');
    $phone    = trim($_POST['phone']     ?? '');
    $formType = trim($_POST['formType']  ?? 'General Enquiry');
    $message  = trim($_POST['message']   ?? '');

    if ($name === '' || $email === '') {
        redirect('../', 'Name and email are required.');
    }

    $subject = $formType === 'Signup from Website'
        ? 'Signup from Website'
        : 'Contact Form Request';

    try {
        $mail = new PHPMailer(true);

        /* ---------- SMTP ---------- */
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->Port       = 587;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        // prefer app-password from .env, else constant
        $mail->Password   = getenv('SMTP_PASSWORD') ?: SMTP_APP_PWD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

        /* ---------- Recipients ---------- */
        $mail->setFrom(INTERNAL_MAIL, APP_NAME);
        $mail->addReplyTo($email, $name);
        $mail->addAddress(INTERNAL_MAIL);

        /* ---------- Content ---------- */
        $meta = "
            <strong>IP:</strong> {$ip}<br>
            <strong>Location:</strong> {$city}, {$region}, {$country}<br>
            <strong>Coords:</strong> {$loc}<br>
            <strong>Org:</strong> {$org}<br>
            <strong>Referrer:</strong> {$referrer}
        ";

        $body = "
            <strong>Name:</strong> {$name}<br>
            <strong>Email:</strong> {$email}<br>
            <strong>Phone:</strong> {$phone}<br><br>
            <strong>Message:</strong><br>
            <p>{$message}</p>
            <hr>{$meta}
        ";

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags(str_replace('<br>', PHP_EOL, $body));

        $mail->send();
        redirect('../thankyou');

    } catch (Exception $e) {
        logError('Mailer Error: ' . $e->getMessage());
        redirect('../', 'Mail could not be sent. Please try again.');
    }
}

redirect('../');
