<?php
// functions.php - Complete Functions Library for BMYA System

// ============================================
// SESSION & AUTHENTICATION FUNCTIONS
// ============================================

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

/**
 * Check if user is admin
 * @return bool
 */
function isAdmin() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
}

/**
 * Redirect if not logged in
 */
function redirectIfNotLoggedIn() {
    if (!isLoggedIn()) {
        $_SESSION['redirect_url'] = $_SERVER['REQUEST_URI'];
        header('Location: ' . SITE_URL . 'login.php');
        exit;
    }
}

/**
 * Redirect if not admin
 */
function redirectIfNotAdmin() {
    if (!isAdmin()) {
        header('Location: ' . SITE_URL . 'login.php');
        exit;
    }
}

/**
 * Check if user has permission for specific action
 * @param string $permission
 * @return bool
 */
function hasPermission($permission) {
    if (isAdmin()) return true;
    // Add more permission checks as needed
    return false;
}

// ============================================
// MEMBERSHIP FUNCTIONS
// ============================================

/**
 * Generate unique membership number
 * @return string
 */
function generateMembershipNumber() {
    $prefix = 'BMYA';
    $year = date('Y');
    $random = strtoupper(substr(uniqid(), -6));
    return $prefix . '/' . $year . '/' . $random;
}

/**
 * Get member data by ID
 * @param PDO $pdo
 * @param int $memberId
 * @return array|null
 */
function getMemberData($pdo, $memberId) {
    try {
        $stmt = $pdo->prepare("SELECT m.*, mt.type as membership_type_name, mt.amount as membership_amount 
                              FROM members m 
                              LEFT JOIN membership_types mt ON m.membership_type_id = mt.id 
                              WHERE m.id = ?");
        $stmt->execute([$memberId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * Get member data by email
 * @param PDO $pdo
 * @param string $email
 * @return array|null
 */
function getMemberByEmail($pdo, $email) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM members WHERE email = ?");
        $stmt->execute([$email]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * Get membership status based on expiry date
 * @param string|null $expiryDate
 * @return array
 */
function getMembershipStatus($expiryDate) {
    if (!$expiryDate || $expiryDate == '0000-00-00') {
        return ['status' => 'Lifetime', 'class' => 'success'];
    }
    
    $today = new DateTime();
    $expiry = new DateTime($expiryDate);
    
    if ($expiry < $today) {
        return ['status' => 'Expired', 'class' => 'danger'];
    }
    
    $diff = $today->diff($expiry)->days;
    if ($diff <= 30) {
        return ['status' => 'Expiring Soon', 'class' => 'warning'];
    }
    
    return ['status' => 'Active', 'class' => 'success'];
}

/**
 * Calculate member age from DOB
 * @param string|null $dob
 * @return int|null
 */
function calculateAge($dob) {
    if (!$dob || $dob == '0000-00-00') return null;
    $birthDate = new DateTime($dob);
    $today = new DateTime();
    return $today->diff($birthDate)->y;
}

// ============================================
// FORMATTING FUNCTIONS
// ============================================

/**
 * Format date to readable format
 * @param string|null $date
 * @param string $format
 * @return string
 */
function formatDate($date, $format = 'd M Y') {
    if (!$date || $date == '0000-00-00' || $date == '') {
        return 'N/A';
    }
    return date($format, strtotime($date));
}

/**
 * Format currency amount
 * @param float $amount
 * @return string
 */
function formatCurrency($amount) {
    return '₹' . number_format($amount, 2);
}

/**
 * Format phone number
 * @param string|null $phone
 * @return string
 */
function formatPhone($phone) {
    if (!$phone) return 'N/A';
    // Remove non-digits
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) == 10) {
        return substr($phone, 0, 5) . '-' . substr($phone, 5);
    }
    return $phone;
}

/**
 * Truncate text to specific length
 * @param string $text
 * @param int $length
 * @param string $suffix
 * @return string
 */
function truncateText($text, $length = 100, $suffix = '...') {
    if (strlen($text) <= $length) return $text;
    return substr($text, 0, $length) . $suffix;
}

/**
 * Generate random string
 * @param int $length
 * @return string
 */
function generateRandomString($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    return substr(str_shuffle($chars), 0, $length);
}

// ============================================
// FILE UPLOAD FUNCTIONS
// ============================================

/**
 * Upload file with validation
 * @param array $file
 * @param string $type
 * @return array
 */
function uploadFile($file, $type = 'photo') {
    $uploadDir = UPLOAD_PATH;
    
    // Create directory if not exists
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    // Allowed file types
    $allowedTypes = [
        'photo' => ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'],
        'document' => ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
        'banner' => ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
    ];
    
    $allowed = $allowedTypes[$type] ?? $allowedTypes['photo'];
    
    // Validate file type
    if (!in_array($file['type'], $allowed)) {
        return ['error' => 'Invalid file type. Please upload JPG, PNG, or GIF only.'];
    }
    
    // Validate file size (max 2MB)
    if ($file['size'] > 2 * 1024 * 1024) {
        return ['error' => 'File too large. Maximum size is 2MB.'];
    }
    
    // Generate unique filename
    $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $filename = time() . '_' . uniqid() . '.' . $extension;
    $filepath = $uploadDir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return ['success' => true, 'filename' => $filename];
    }
    
    return ['error' => 'Failed to upload file. Please try again.'];
}

/**
 * Delete file from server
 * @param string $filename
 * @return bool
 */
function deleteFile($filename) {
    if (!$filename || $filename == 'default.jpg') return true;
    $filepath = UPLOAD_PATH . $filename;
    if (file_exists($filepath)) {
        return unlink($filepath);
    }
    return true;
}

// ============================================
// DATABASE QUERY FUNCTIONS
// ============================================

/**
 * Get system setting by key
 * @param PDO $pdo
 * @param string $key
 * @return string
 */
function getSystemSetting($pdo, $key) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['setting_value'] : '';
    } catch (PDOException $e) {
        return '';
    }
}

/**
 * Get dashboard statistics
 * @param PDO $pdo
 * @return array
 */
function getDashboardStats($pdo) {
    $stats = [
        'total_members' => 0,
        'new_members' => 0,
        'total_revenue' => 0,
        'upcoming_events' => 0,
        'expiring_members' => 0,
        'active_members' => 0
    ];
    
    try {
        // Total members
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM members");
        $stats['total_members'] = $stmt->fetch()['count'] ?? 0;
        
        // Active members
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM members WHERE status = 'active'");
        $stats['active_members'] = $stmt->fetch()['count'] ?? 0;
        
        // New members this month
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM members WHERE MONTH(join_date) = MONTH(CURDATE()) AND YEAR(join_date) = YEAR(CURDATE())");
        $stats['new_members'] = $stmt->fetch()['count'] ?? 0;
        
        // Total revenue
        $stmt = $pdo->query("SELECT SUM(amount) as total FROM renewals WHERE status = 'completed'");
        $stats['total_revenue'] = $stmt->fetch()['total'] ?? 0;
        
        // Upcoming events
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM events WHERE event_date >= CURDATE() AND status = 'upcoming'");
        $stats['upcoming_events'] = $stmt->fetch()['count'] ?? 0;
        
        // Expiring members next 30 days
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM members WHERE expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)");
        $stmt->execute();
        $stats['expiring_members'] = $stmt->fetch()['count'] ?? 0;
        
    } catch (PDOException $e) {
        // Return default values
    }
    
    return $stats;
}

/**
 * Get all membership types
 * @param PDO $pdo
 * @return array
 */
function getMembershipTypes($pdo) {
    try {
        $stmt = $pdo->query("SELECT * FROM membership_types ORDER BY amount ASC");
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Get upcoming events
 * @param PDO $pdo
 * @param int $limit
 * @return array
 */
function getUpcomingEvents($pdo, $limit = 5) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM events WHERE event_date >= CURDATE() AND status = 'upcoming' ORDER BY event_date ASC LIMIT ?");
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Get member renewal history
 * @param PDO $pdo
 * @param int $memberId
 * @param int $limit
 * @return array
 */
function getMemberRenewals($pdo, $memberId, $limit = 10) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM renewals WHERE member_id = ? ORDER BY renewal_date DESC LIMIT ?");
        $stmt->execute([$memberId, $limit]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Get member registered events
 * @param PDO $pdo
 * @param int $memberId
 * @return array
 */
function getMemberEvents($pdo, $memberId) {
    try {
        $stmt = $pdo->prepare("SELECT e.*, er.registration_date 
                              FROM events e 
                              JOIN event_registrations er ON e.id = er.event_id 
                              WHERE er.member_id = ? AND e.event_date >= CURDATE()
                              ORDER BY e.event_date ASC");
        $stmt->execute([$memberId]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

// ============================================
// EMAIL FUNCTIONS
// ============================================

/**
 * Send email using PHP mail function
 * @param string $to
 * @param string $subject
 * @param string $message
 * @param string $fromName
 * @param string $fromEmail
 * @return bool
 */
function sendEmail($to, $subject, $message, $fromName = '', $fromEmail = '') {
    $fromName = $fromName ?: SITE_NAME;
    $fromEmail = $fromEmail ?: SITE_EMAIL;
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: " . $fromName . " <" . $fromEmail . ">\r\n";
    $headers .= "Reply-To: " . $fromEmail . "\r\n";
    
    return mail($to, $subject, $message, $headers);
}

/**
 * Send welcome email to new member
 * @param PDO $pdo
 * @param array $member
 * @param string $password
 * @return bool
 */
function sendWelcomeEmail($pdo, $member, $password = '') {
    $subject = "Welcome to " . SITE_NAME;
    
    $message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #2c3e50; color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background: #f9f9f9; }
            .footer { text-align: center; padding: 20px; font-size: 12px; color: #666; }
            .button { display: inline-block; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 5px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>Welcome to " . SITE_NAME . "</h2>
            </div>
            <div class='content'>
                <p>Dear <strong>" . htmlspecialchars($member['fullname']) . "</strong>,</p>
                <p>Thank you for joining " . SITE_NAME . ". Your membership has been successfully registered.</p>
                <p><strong>Membership Details:</strong></p>
                <ul>
                    <li>Membership Number: <strong>" . $member['membership_number'] . "</strong></li>
                    <li>Membership Type: <strong>" . ($member['membership_type_name'] ?? 'N/A') . "</strong></li>
                    <li>Valid Until: <strong>" . formatDate($member['expiry_date']) . "</strong></li>
                </ul>
                " . ($password ? "<p><strong>Login Password:</strong> " . $password . "</p>" : "") . "
                <p>You can now login to your dashboard to access your digital ID card and other benefits.</p>
                <p style='text-align: center;'>
                    <a href='" . SITE_URL . "login.php' class='button'>Login to Dashboard</a>
                </p>
                <p>Best regards,<br>" . SITE_NAME . " Team</p>
            </div>
            <div class='footer'>
                <p>&copy; " . date('Y') . " " . SITE_NAME . ". All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    return sendEmail($member['email'], $subject, $message);
}

// ============================================
// NOTIFICATION FUNCTIONS
// ============================================

/**
 * Create notification for user
 * @param PDO $pdo
 * @param int $userId
 * @param string $title
 * @param string $message
 * @param string $type
 * @return bool
 */
function createNotification($pdo, $userId, $title, $message, $type = 'info') {
    try {
        $stmt = $pdo->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (?, ?, ?, ?)");
        return $stmt->execute([$userId, $title, $message, $type]);
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Get unread notifications count
 * @param PDO $pdo
 * @param int $userId
 * @return int
 */
function getUnreadNotificationCount($pdo, $userId) {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
        $stmt->execute([$userId]);
        return $stmt->fetch()['count'] ?? 0;
    } catch (PDOException $e) {
        return 0;
    }
}

// ============================================
// VALIDATION FUNCTIONS
// ============================================

/**
 * Validate email address
 * @param string $email
 * @return bool
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Validate phone number (Indian)
 * @param string $phone
 * @return bool
 */
function validatePhone($phone) {
    return preg_match('/^[6-9]\d{9}$/', $phone);
}

/**
 * Validate password strength
 * @param string $password
 * @return array
 */
function validatePasswordStrength($password) {
    $strength = 0;
    $messages = [];
    
    if (strlen($password) >= 8) {
        $strength++;
    } else {
        $messages[] = 'Password must be at least 8 characters long';
    }
    
    if (preg_match('/[A-Z]/', $password)) {
        $strength++;
    } else {
        $messages[] = 'Password should contain at least one uppercase letter';
    }
    
    if (preg_match('/[a-z]/', $password)) {
        $strength++;
    } else {
        $messages[] = 'Password should contain at least one lowercase letter';
    }
    
    if (preg_match('/[0-9]/', $password)) {
        $strength++;
    } else {
        $messages[] = 'Password should contain at least one number';
    }
    
    if (preg_match('/[^A-Za-z0-9]/', $password)) {
        $strength++;
    } else {
        $messages[] = 'Password should contain at least one special character';
    }
    
    $level = 'Weak';
    if ($strength >= 4) $level = 'Strong';
    elseif ($strength >= 3) $level = 'Good';
    elseif ($strength >= 2) $level = 'Fair';
    
    return [
        'score' => $strength,
        'level' => $level,
        'messages' => $messages
    ];
}

// ============================================
// SECURITY FUNCTIONS
// ============================================

/**
 * Sanitize input data
 * @param string $data
 * @return string
 */
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

/**
 * Generate CSRF token
 * @return string
 */
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Verify CSRF token
 * @param string $token
 * @return bool
 */
function verifyCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Generate password reset token
 * @return string
 */
function generateResetToken() {
    return bin2hex(random_bytes(32));
}

// ============================================
// LOGGING FUNCTIONS
// ============================================

/**
 * Log user activity
 * @param PDO $pdo
 * @param int $userId
 * @param string $action
 * @param string|null $details
 * @return bool
 */
function logActivity($pdo, $userId, $action, $details = null) {
    try {
        $ip = $_SERVER['REMOTE_ADDR'] ?? null;
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
        
        $stmt = $pdo->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent) VALUES (?, ?, ?, ?, ?)");
        return $stmt->execute([$userId, $action, $details, $ip, $userAgent]);
    } catch (PDOException $e) {
        return false;
    }
}

// ============================================
// UTILITY FUNCTIONS
// ============================================

/**
 * Get current page URL
 * @return string
 */
function getCurrentURL() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    return $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

/**
 * Redirect to URL
 * @param string $url
 */
function redirect($url) {
    header('Location: ' . $url);
    exit;
}

/**
 * Display alert message
 * @param string $message
 * @param string $type
 */
function showAlert($message, $type = 'success') {
    echo "<div class='alert alert-{$type} alert-dismissible fade show' role='alert'>
            <i class='fas fa-" . ($type == 'success' ? 'check-circle' : 'exclamation-triangle') . " me-2'></i>
            {$message}
            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
          </div>";
}

/**
 * Debug function (for development only)
 * @param mixed $data
 */
function debug($data) {
    echo '<pre>';
    var_dump($data);
    echo '</pre>';
}

/**
 * Check if table exists in database
 * @param PDO $pdo
 * @param string $tableName
 * @return bool
 */
function tableExists($pdo, $tableName) {
    try {
        $stmt = $pdo->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$tableName]);
        return $stmt->rowCount() > 0;
    } catch (PDOException $e) {
        return false;
    }
}
?>