<?php
// Shared helper functions for PHP form handlers.

require_once __DIR__ . '/config.php';

function send_json($status, $payload) {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    if (defined('ALLOWED_ORIGIN') && ALLOWED_ORIGIN !== '') {
        header('Access-Control-Allow-Origin: ' . ALLOWED_ORIGIN);
    }
    echo json_encode($payload);
    exit;
}

function require_post() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        send_json(405, ['ok' => false, 'error' => 'Method not allowed']);
    }
}

function clean($v, $maxLen = 5000) {
    if (!is_string($v)) return '';
    $v = trim($v);
    if (strlen($v) > $maxLen) $v = substr($v, 0, $maxLen);
    // Strip control chars except newline/tab
    $v = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $v);
    return $v;
}

function clean_email($v) {
    $v = clean($v, 255);
    return filter_var($v, FILTER_VALIDATE_EMAIL) ? $v : '';
}

function verify_recaptcha($token) {
    if (!$token) return false;
    if (!RECAPTCHA_SECRET) return false;

    $data = http_build_query([
        'secret'   => RECAPTCHA_SECRET,
        'response' => $token,
        'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
    ]);

    // Try cURL first (most cPanel hosts have it)
    if (function_exists('curl_init')) {
        $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $resp = curl_exec($ch);
        curl_close($ch);
    } else {
        $opts = ['http' => [
            'method'  => 'POST',
            'header'  => 'Content-Type: application/x-www-form-urlencoded',
            'content' => $data,
            'timeout' => 10,
        ]];
        $resp = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, stream_context_create($opts));
    }

    if (!$resp) return false;
    $json = json_decode($resp, true);
    return is_array($json) && !empty($json['success']);
}

function send_email($subject, $bodyText, $attachment = null) {
    $boundary = '==BOUNDARY_' . md5(uniqid('', true));

    $headers   = [];
    $headers[] = 'From: ' . FROM_NAME . ' <' . FROM_EMAIL . '>';
    $headers[] = 'Reply-To: ' . FROM_EMAIL;
    $headers[] = 'MIME-Version: 1.0';

    if ($attachment && !empty($attachment['tmp_name']) && is_uploaded_file($attachment['tmp_name'])) {
        $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
        $body  = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
        $body .= $bodyText . "\r\n\r\n";

        $fileData = file_get_contents($attachment['tmp_name']);
        $encoded  = chunk_split(base64_encode($fileData));
        $fileName = preg_replace('/[^A-Za-z0-9._-]/', '_', $attachment['name']);
        $mime     = $attachment['type'] ?: 'application/octet-stream';

        $body .= "--$boundary\r\n";
        $body .= "Content-Type: $mime; name=\"$fileName\"\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n";
        $body .= "Content-Disposition: attachment; filename=\"$fileName\"\r\n\r\n";
        $body .= $encoded . "\r\n";
        $body .= "--$boundary--";
    } else {
        $headers[] = 'Content-Type: text/plain; charset=UTF-8';
        $body = $bodyText;
    }

    $cleanSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
    return @mail(RECIPIENT_EMAIL, $cleanSubject, $body, implode("\r\n", $headers));
}
