<?php
/**
 * Global Helper Functions
 */

/**
 * 1. Mailchimp Notification Trigger
 * This sends an email via Mailchimp when a new drama or member is added.
 * Note: Requires a Mailchimp API Key and List ID.
 */
function sendMailchimpNotification($subject, $content) {
    // Replace with your actual Mailchimp details
    $api_key = 'YOUR_MAILCHIMP_API_KEY';
    $list_id = 'YOUR_LIST_ID';
    $server_prefix = 'usX'; // e.g., us21

    $url = "https://{$server_prefix}.api.mailchimp.com/3.0/lists/{$list_id}/messages";

    // This is a simplified logic. For internal use, standard PHP mail() is 
    // often more reliable unless you are sending to thousands of people.
    $admin_email = "admin@swarnawahini.lk";
    $headers = "From: " . $admin_email . "\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

    // Fallback to standard mail if API key is not set
    return mail("committee-members@swarnawahini.lk", $subject, $content, $headers);
}

/**
 * 2. Sanitize Iframe Code
 * Ensures the admin-pasted iframe is responsive and secure.
 */
function renderIframe($raw_html) {
    // Add Bootstrap's responsive classes if they aren't there
    if (strpos($raw_html, 'class=') === false) {
        $raw_html = str_replace('<iframe', '<iframe class="embed-responsive-item"', $raw_html);
    }
    return $raw_html;
}

/**
 * 3. Calculate Performance
 * Used in the Admin Dashboard to see how many episodes a member has rated.
 */
function getMemberProgress($pdo, $user_id) {
    // Total Episodes available
    $total_stmt = $pdo->query("SELECT COUNT(*) FROM episodes");
    $total = $total_stmt->fetchColumn();

    // Episodes rated by this user
    $rated_stmt = $pdo->prepare("SELECT COUNT(*) FROM ratings WHERE user_id = ?");
    $rated_stmt->execute([$user_id]);
    $rated = $rated_stmt->fetchColumn();

    if ($total == 0) return 0;
    return ($rated / $total) * 100;
}

/**
 * 4. Human-readable Date
 */
function timeAgo($timestamp) {
    $time = strtotime($timestamp);
    $current = time();
    $diff = $current - $time;
    
    if ($diff < 60) return "Just now";
    if ($diff < 3600) return round($diff/60) . " mins ago";
    if ($diff < 86400) return round($diff/3600) . " hours ago";
    return date("M j, g:i a", $time);
}