<?php
// Production Environment Isolation: Enforce error isolation
define('IS_DEV', false);

if (!IS_DEV) {
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    error_reporting(0);
} else {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

// Setup CORS headers with explicit allowance for X-App-Signature
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-App-Signature");

// Handle preflight OPTIONS requests instantly
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$db_host = "localhost";
$db_user = "kyrmifsd_thinkrich_db";
$db_pass = "^BdZz~LjKiub}?Ii";
$db_name = "kyrmifsd_thinkrich_db";

function getDBConnection()
{
    global $db_host, $db_user, $db_pass, $db_name;
    try {
        $conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        return $conn;
    } catch (PDOException $e) {
        logSecurityError("Database connection failure: " . $e->getMessage());
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Database connection failure. Please try again later."]);
        exit();
    }
}

// Secure Private Log Helper
function logSecurityError($message)
{
    $logDir = __DIR__ . '/logs';
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    $logFile = $logDir . '/security_errors.log';
    $timestamp = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $method = $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN';
    $uri = $_SERVER['REQUEST_URI'] ?? 'UNKNOWN';
    $formattedMessage = "[$timestamp] [IP: $ip] [Method: $method] [URI: $uri] - $message" . PHP_EOL;
    file_put_contents($logFile, $formattedMessage, FILE_APPEND);
}

// polyfill getallheaders if not exists
if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

// Request Signature Validation (Official App Verifier)
define('APP_SIGNATURE_KEY', 'ThinkRichNaijaEnterpriseKey2026!');

function validateRequestSignature()
{
    // Bypass for server preflights and self setup scripts
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS' || basename($_SERVER['SCRIPT_NAME']) === 'setup.php') {
        return true;
    }

    $headers = array_change_key_case(getallheaders(), CASE_LOWER);
    $signature = $headers['x-app-signature'] ?? '';

    if (empty($signature) || $signature !== APP_SIGNATURE_KEY) {
        logSecurityError("Blocked Request - Invalid or missing X-App-Signature header.");
        http_response_code(403);
        echo json_encode(["status" => "error", "message" => "Access Forbidden: Invalid API request source."]);
        exit();
    }
}

// Centralized IP Rate Limiter
function checkRateLimit($endpoint, $maxAttempts = 5, $decaySeconds = 60)
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    try {
        $db = getDBConnection();

        // 1. Clean up stale logs older than decay period
        $stmt = $db->prepare("DELETE FROM rate_limits WHERE last_request < (NOW() - INTERVAL ? SECOND)");
        $stmt->execute([$decaySeconds]);

        // 2. Fetch current attempts count
        $stmt = $db->prepare("SELECT attempts FROM rate_limits WHERE ip_address = ? AND endpoint = ?");
        $stmt->execute([$ip, $endpoint]);
        $record = $stmt->fetch();

        if ($record) {
            $attempts = intval($record['attempts']);
            if ($attempts >= $maxAttempts) {
                logSecurityError("Rate Limit Exceeded - IP: $ip for endpoint: $endpoint (Attempts: $attempts)");
                http_response_code(429);
                echo json_encode([
                    "status" => "error",
                    "message" => "Too many attempts. Please wait a minute and try again."
                ]);
                exit();
            }

            // Update attempts
            $stmt = $db->prepare("UPDATE rate_limits SET attempts = attempts + 1 WHERE ip_address = ? AND endpoint = ?");
            $stmt->execute([$ip, $endpoint]);
        } else {
            // First attempt
            $stmt = $db->prepare("INSERT INTO rate_limits (ip_address, endpoint, attempts) VALUES (?, ?, 1)");
            $stmt->execute([$ip, $endpoint]);
        }
    } catch (Exception $e) {
        logSecurityError("Rate limiter failure: " . $e->getMessage());
    }
}

// Robust Sanitization Helper
function sanitizeInput($input)
{
    if (is_array($input)) {
        return array_map('sanitizeInput', $input);
    }
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

// Dynamically fetch user winnings for today's date from ledger
function getTodayWinnings($userId)
{
    try {
        $db = getDBConnection();
        $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM wallet_transactions WHERE user_id = ? AND action = 'reward' AND DATE(created_at) = CURDATE()");
        $stmt->execute([$userId]);
        return floatval($stmt->fetchColumn());
    } catch (Exception $e) {
        return 0.00;
    }
}

// ==========================================
// SMTP PHPMailer Configuration Settings
// ==========================================
define('SMTP_HOST', 'mail.thinkrichnaija.com');
define('SMTP_PORT', 465);
define('SMTP_ENCRYPTION', 'ssl');
define('SMTP_USER', 'noreply@thinkrichnaija.com');
define('SMTP_PASS', '+Au1vdhTR8)9%+}A');
define('SMTP_FROM_EMAIL', 'noreply@thinkrichnaija.com');
define('SMTP_FROM_NAME', 'Think Rich Naija');

// Centralized PHP Mailer Dispatcher Helper
require_once __DIR__ . '/phpmailer/Exception.php';
require_once __DIR__ . '/phpmailer/PHPMailer.php';
require_once __DIR__ . '/phpmailer/SMTP.php';

function sendEmail($to, $subject, $body)
{
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = SMTP_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = SMTP_USER;
        $mail->Password = SMTP_PASS;

        // Resolve nested ternary check
        if (SMTP_ENCRYPTION === 'ssl') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else if (SMTP_ENCRYPTION === 'tls') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        } else {
            $mail->SMTPSecure = '';
        }

        $mail->Port = SMTP_PORT;

        // Custom SSL parameters (prevents certificate errors on local XAMPP/Windows installations)
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        // Recipients
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $body;
        // Text fallback
        $mail->AltBody = strip_tags($body);

        $mail->send();
        return true;
    } catch (Exception $e) {
        logSecurityError("Mailer Dispatch Error: " . $mail->ErrorInfo);
        return false;
    }
}

// Force secure signature verification globally on import
validateRequestSignature();
?>