<?php
/**
 * Core System Functions & Helpers
 * Location: public_html/includes/functions.php
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Sanitize string input
 */
function sanitize_input($data) {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

/**
 * Check if user is logged in
 */
function is_logged_in() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

/**
 * Require login to access protected pages
 */
function require_login() {
    if (!is_logged_in()) {
        header("Location: /public_html/login.php?error=" . urlencode("Please login to access your account."));
        exit;
    }
}

/**
 * Generate secure random token
 */
function generate_token($length = 32) {
    return bin2hex(random_bytes($length));
}

/**
 * Send email function (Uses native mail() or fallback logging for XAMPP local dev)
 */
function send_verification_email($email, $name, $verification_link) {
    $subject = "Verify your MiBuildqc Account";
    $message = "Hello {$name},

";
    $message .= "Thank you for registering with MiBuildqc!
";
    $message .= "Please click the link below to verify your email address:
";
    $message .= "{$verification_link}

";
    $message .= "If you did not create an account, please ignore this email.
";
    $headers = "From: no-reply@mibuildqc.local
" .
               "Reply-To: support@mibuildqc.local
" .
               "X-Mailer: PHP/" . phpversion();

    // Try standard PHP mail() function
    @mail($email, $subject, $message, $headers);
    
    // Save to local log file for testing when XAMPP SMTP is not configured
    $log_entry = "[" . date('Y-m-d H:i:s') . "] TO: {$email} | LINK: {$verification_link}
";
    @file_put_contents(__DIR__ . '/../mail_debug.log', $log_entry, FILE_APPEND);
}

/**
 * Send team invitation email
 */
function send_team_invitation_email($email, $name, $company_name, $invite_link) {
    $subject = "You have been invited to join {$company_name} on MiBuildqc";
    $salutation = !empty($name) ? "Hello {$name}," : "Hello,";
    $message = "{$salutation}

";
    $message .= "You have been invited to join {$company_name}'s quality control team on MiBuildqc.
";
    $message .= "Please click the link below to set up your team password and activate your access:
";
    $message .= "{$invite_link}

";
    $headers = "From: no-reply@mibuildqc.local
" .
               "X-Mailer: PHP/" . phpversion();

    @mail($email, $subject, $message, $headers);
    
    $log_entry = "[" . date('Y-m-d H:i:s') . "] INVITE TO: {$email} ({$name}) | LINK: {$invite_link}
";
    @file_put_contents(__DIR__ . '/../mail_debug.log', $log_entry, FILE_APPEND);
}
?>