<?php
/**
 * UI Components - Modular Components for TutorKita
 * Sistem Pengurusan Tutor
 */

// Profile Images Array
define('PROFILE_EMOJIS', [
    '👦' => 'Budak Lelaki',
    '👧' => 'Budak Perempuan',
    '👨‍🎓' => 'Pelajar',
    '👩‍🏫' => 'Guru',
    '👨‍💼' => 'Admin'
]);

// Subjects Array
define('SUBJECTS', [
    'Matematik' => '📐 Matematik',
    'Bahasa Melayu' => '📝 Bahasa Melayu',
    'Bahasa Inggeris' => '📚 Bahasa Inggeris',
    'Sains' => '🔬 Sains',
    'Sejarah' => '🏛️ Sejarah',
    'Geografi' => '🌍 Geografi',
    'Fizik' => '⚛️ Fizik',
    'Kimia' => '🧪 Kimia',
    'Biologi' => '🧬 Biologi',
    'Pendidikan Islam' => '☪️ Pendidikan Islam',
    'Lain-lain' => '➕ Lain-lain'
]);

// Days Array
define('DAYS', [
    'Isnin' => 'Isnin',
    'Selasa' => 'Selasa',
    'Rabu' => 'Rabu',
    'Khamis' => 'Khamis',
    'Jumaat' => 'Jumaat',
    'Sabtu' => 'Sabtu',
    'Ahad' => 'Ahad'
]);

/**
 * Render Header Component
 */
function renderHeader($title = 'TutorKita', $subtitle = 'Sistem Pengurusan Tutor') {
    ?>
    <header class="main-header">
        <div class="header-content">
            <div class="logo-section">
                <span class="logo-icon">📚</span>
                <div class="logo-text">
                    <h1><?php echo htmlspecialchars($title); ?></h1>
                    <p><?php echo htmlspecialchars($subtitle); ?></p>
                </div>
            </div>
            <div class="header-actions">
                <div class="notification-bell" id="notificationBell">
                    <span>🔔</span>
                    <span class="notification-count" id="notificationCount">0</span>
                </div>
                <div class="user-profile" id="userProfile">
                    <span class="profile-emoji" id="headerProfileEmoji">👨‍💼</span>
                    <span class="profile-name" id="headerProfileName">Admin</span>
                    <span class="dropdown-arrow">▼</span>
                </div>
            </div>
        </div>
    </header>
    <?php
}

/**
 * Render Welcome Banner
 */
function renderWelcomeBanner($greeting = 'Selamat Sejahtera', $name = 'Cikgu', $additionalInfo = '') {
    $hour = date('H');
    $timeGreeting = '';
    if ($hour < 12) {
        $timeGreeting = '☀️ Selamat Pagi';
    } elseif ($hour < 17) {
        $timeGreeting = '🌤️ Selamat Petang';
    } else {
        $timeGreeting = '🌙 Selamat Malam';
    }
    ?>
    <div class="welcome-banner">
        <div class="welcome-content">
            <div class="welcome-icon">👋</div>
            <div class="welcome-text">
                <h2><?php echo $greeting; ?>, <?php echo htmlspecialchars($name); ?>!</h2>
                <p><?php echo $timeGreeting; ?></p>
                <?php if ($additionalInfo): ?>
                    <p class="additional-info"><?php echo $additionalInfo; ?></p>
                <?php endif; ?>
            </div>
        </div>
        <div class="welcome-decoration">
            <span class="decoration-emoji">✨</span>
        </div>
    </div>
    <?php
}

/**
 * Render Statistics Cards
 */
function renderStatsCards($stats = []) {
    $defaultStats = [
        [
            'icon' => '👥',
            'value' => '0',
            'label' => 'Jumlah',
            'color' => 'primary',
            'gradient' => 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
        ],
        [
            'icon' => '📊',
            'value' => '0',
            'label' => 'Statistik',
            'color' => 'success',
            'gradient' => 'linear-gradient(135deg, #10b981 0%, #059669 100%)'
        ],
        [
            'icon' => '📈',
            'value' => '0',
            'label' => 'Aktiviti',
            'color' => 'warning',
            'gradient' => 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)'
        ],
        [
            'icon' => '💡',
            'value' => '0',
            'label' => 'Info',
            'color' => 'info',
            'gradient' => 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
        ]
    ];

    $stats = array_merge($defaultStats, $stats);
    ?>
    <div class="stats-grid">
        <?php foreach ($stats as $index => $stat): ?>
            <div class="stat-card" style="--card-gradient: <?php echo $stat['gradient']; ?>">
                <div class="stat-icon"><?php echo $stat['icon']; ?></div>
                <div class="stat-content">
                    <div class="stat-value" data-value="<?php echo $stat['value']; ?>"><?php echo $stat['value']; ?></div>
                    <div class="stat-label"><?php echo $stat['label']; ?></div>
                </div>
                <div class="stat-bg-icon"><?php echo $stat['icon']; ?></div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
}

/**
 * Render Tab Navigation
 */
function renderTabs($tabs = [], $activeTab = 'tab1') {
    ?>
    <div class="tabs-container">
        <div class="tabs-header">
            <?php foreach ($tabs as $index => $tab): ?>
                <button class="tab-btn <?php echo ($activeTab === $tab['id']) ? 'active' : ''; ?>" 
                        data-tab="<?php echo $tab['id']; ?>"
                        data-icon="<?php echo $tab['icon'] ?? '📄'; ?>">
                    <span class="tab-icon"><?php echo $tab['icon'] ?? '📄'; ?></span>
                    <span class="tab-label"><?php echo $tab['label']; ?></span>
                </button>
            <?php endforeach; ?>
        </div>
        <div class="tabs-content">
            <?php foreach ($tabs as $tab): ?>
                <div class="tab-panel <?php echo ($activeTab === $tab['id']) ? 'active' : ''; ?>" id="<?php echo $tab['id']; ?>">
                    <?php if (isset($tab['content'])) echo $tab['content']; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/**
 * Render Card Component
 */
function renderCard($title = '', $icon = '📋', $content = '', $class = '') {
    ?>
    <div class="card <?php echo $class; ?>">
        <div class="card-header">
            <h3 class="card-title">
                <span class="card-icon"><?php echo $icon; ?></span>
                <?php echo htmlspecialchars($title); ?>
            </h3>
        </div>
        <div class="card-body">
            <?php echo $content; ?>
        </div>
    </div>
    <?php
}

/**
 * Render Form Input
 */
function renderFormInput($params = []) {
    $defaults = [
        'type' => 'text',
        'name' => '',
        'label' => '',
        'placeholder' => '',
        'value' => '',
        'required' => false,
        'min' => '',
        'max' => '',
        'options' => [],
        'checkbox_items' => [],
        'class' => '',
        'id' => ''
    ];

    $params = array_merge($defaults, $params);
    $id = $params['id'] ?: 'field_' . $params['name'];
    $required = $params['required'] ? ' required' : '';
    $minAttr = $params['min'] ? ' min="' . $params['min'] . '"' : '';
    $maxAttr = $params['max'] ? ' max="' . $params['max'] . '"' : '';
    ?>
    <div class="form-group <?php echo $params['class']; ?>" id="<?php echo $id; ?>_group">
        <?php if ($params['label']): ?>
            <label for="<?php echo $id; ?>">
                <?php echo htmlspecialchars($params['label']); ?>
                <?php if ($params['required']): ?>
                    <span class="required-mark">*</span>
                <?php endif; ?>
            </label>
        <?php endif; ?>

        <?php if ($params['type'] === 'select'): ?>
            <select name="<?php echo $params['name']; ?>" id="<?php echo $id; ?>" class="form-control"<?php echo $required; ?>>
                <option value="">-- Sila Pilih --</option>
                <?php foreach ($params['options'] as $value => $label): ?>
                    <option value="<?php echo htmlspecialchars($value); ?>" 
                        <?php echo ($params['value'] == $value) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        
        <?php elseif ($params['type'] === 'textarea'): ?>
            <textarea name="<?php echo $params['name']; ?>" id="<?php echo $id; ?>" 
                      class="form-control" placeholder="<?php echo htmlspecialchars($params['placeholder']); ?>"
                      <?php echo $required; ?>><?php echo htmlspecialchars($params['value']); ?></textarea>
        
        <?php elseif ($params['type'] === 'checkbox-group'): ?>
            <div class="checkbox-group">
                <?php foreach ($params['checkbox_items'] as $index => $item): ?>
                    <label class="checkbox-item">
                        <input type="checkbox" 
                               name="<?php echo $params['name']; ?>[]" 
                               value="<?php echo htmlspecialchars($item['value']); ?>"
                               <?php echo ($item['value'] === 'Lain-lain') ? 'class="other-subject-checkbox"' : ''; ?>
                               <?php echo (in_array($item['value'], (array)$params['value'])) ? 'checked' : ''; ?>>
                        <span class="checkmark"></span>
                        <span class="checkbox-label"><?php echo $item['label']; ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <div class="other-input-container" style="display: none; margin-top: 10px;">
                <input type="text" name="<?php echo $params['name']; ?>_other" 
                       class="form-control" placeholder="Sila nyatakan..."
                       id="<?php echo $id; ?>_other">
            </div>
        
        <?php elseif ($params['type'] === 'radio'): ?>
            <div class="radio-group">
                <?php foreach ($params['options'] as $value => $label): ?>
                    <label class="radio-item">
                        <input type="radio" 
                               name="<?php echo $params['name']; ?>" 
                               value="<?php echo htmlspecialchars($value); ?>"
                               <?php echo ($params['value'] == $value) ? 'checked' : ''; ?>>
                        <span class="radio-mark"></span>
                        <span class="radio-label"><?php echo htmlspecialchars($label); ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        
        <?php else: ?>
            <input type="<?php echo $params['type']; ?>" 
                   name="<?php echo $params['name']; ?>" 
                   id="<?php echo $id; ?>"
                   class="form-control" 
                   value="<?php echo htmlspecialchars($params['value']); ?>"
                   placeholder="<?php echo htmlspecialchars($params['placeholder']); ?>"
                   <?php echo $required . $minAttr . $maxAttr; ?>>
        <?php endif; ?>
        
        <span class="error-message" id="<?php echo $id; ?>_error"></span>
    </div>
    <?php
}

/**
 * Render Profile Emoji Selector
 */
function renderProfileEmojiSelector($name = 'profile_image', $selected = '👦') {
    ?>
    <div class="emoji-selector">
        <label>Pilih Avatar:</label>
        <div class="emoji-options">
            <?php foreach (PROFILE_EMOJIS as $emoji => $label): ?>
                <label class="emoji-option <?php echo ($selected === $emoji) ? 'selected' : ''; ?>">
                    <input type="radio" name="<?php echo $name; ?>" value="<?php echo $emoji; ?>" 
                           <?php echo ($selected === $emoji) ? 'checked' : ''; ?>>
                    <span class="emoji"><?php echo $emoji; ?></span>
                    <span class="emoji-label"><?php echo $label; ?></span>
                </label>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/**
 * Render Button
 */
function renderButton($params = []) {
    $defaults = [
        'type' => 'button',
        'text' => 'Hantar',
        'icon' => '',
        'class' => 'primary',
        'id' => '',
        'onclick' => ''
    ];

    $params = array_merge($defaults, $params);
    $onclickAttr = $params['onclick'] ? ' onclick="' . $params['onclick'] . '"' : '';
    $idAttr = $params['id'] ? ' id="' . $params['id'] . '"' : '';
    ?>
    <button type="<?php echo $params['type']; ?>" 
            class="btn btn-<?php echo $params['class']; ?>"
            <?php echo $idAttr . $onclickAttr; ?>>
        <?php if ($params['icon']): ?>
            <span class="btn-icon"><?php echo $params['icon']; ?></span>
        <?php endif; ?>
        <span class="btn-text"><?php echo $params['text']; ?></span>
    </button>
    <?php
}

/**
 * Render Alert/Notification
 */
function renderAlert($message = '', $type = 'info', $dismissible = true) {
    $icons = [
        'info' => 'ℹ️',
        'success' => '✅',
        'warning' => '⚠️',
        'error' => '❌',
        'alert' => '🚨'
    ];
    $icon = $icons[$type] ?? 'ℹ️';
    ?>
    <div class="alert alert-<?php echo $type; ?>" role="alert">
        <span class="alert-icon"><?php echo $icon; ?></span>
        <span class="alert-message"><?php echo htmlspecialchars($message); ?></span>
        <?php if ($dismissible): ?>
            <button type="button" class="alert-close" onclick="this.parentElement.remove();">&times;</button>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Render Modal
 */
function renderModal($id = 'modal', $title = 'Modal', $content = '', $footer = '') {
    ?>
    <div class="modal-overlay" id="<?php echo $id; ?>_overlay">
        <div class="modal" id="<?php echo $id; ?>">
            <div class="modal-header">
                <h3 class="modal-title"><?php echo htmlspecialchars($title); ?></h3>
                <button type="button" class="modal-close" onclick="closeModal('<?php echo $id; ?>');">&times;</button>
            </div>
            <div class="modal-body">
                <?php echo $content; ?>
            </div>
            <?php if ($footer): ?>
                <div class="modal-footer">
                    <?php echo $footer; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/**
 * Render Data Table
 */
function renderTable($headers = [], $rows = [], $actions = []) {
    ?>
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <?php foreach ($headers as $header): ?>
                        <th><?php echo htmlspecialchars($header); ?></th>
                    <?php endforeach; ?>
                    <?php if (!empty($actions)): ?>
                        <th>Tindakan</th>
                    <?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $row): ?>
                    <tr>
                        <?php foreach ($row as $cell): ?>
                            <td><?php echo $cell; ?></td>
                        <?php endforeach; ?>
                        <?php if (!empty($actions)): ?>
                            <td class="action-cell">
                                <?php foreach ($actions as $action): ?>
                                    <button class="action-btn <?php echo $action['class'] ?? ''; ?>" 
                                            onclick="<?php echo $action['onclick']; ?>"
                                            title="<?php echo $action['title'] ?? ''; ?>">
                                        <?php echo $action['icon'] ?? '⚙️'; ?>
                                    </button>
                                <?php endforeach; ?>
                            </td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
}

/**
 * Render Loading Spinner
 */
function renderLoading($text = 'Sedang memuat...') {
    ?>
    <div class="loading-overlay">
        <div class="loading-spinner">
            <div class="spinner"></div>
            <p><?php echo htmlspecialchars($text); ?></p>
        </div>
    </div>
    <?php
}

/**
 * Render Empty State
 */
function renderEmptyState($icon = '📭', $title = 'Tiada Data', $message = 'Belum ada data untuk dipaparkan.') {
    ?>
    <div class="empty-state">
        <div class="empty-icon"><?php echo $icon; ?></div>
        <h3 class="empty-title"><?php echo htmlspecialchars($title); ?></h3>
        <p class="empty-message"><?php echo htmlspecialchars($message); ?></p>
    </div>
    <?php
}

/**
 * Get Grade Options Based on Education Level
 */
function getGradeOptions($educationLevel = '') {
    if ($educationLevel === 'Sekolah Menengah') {
        return [
            'Tingk. 1' => 'Tingk. 1',
            'Tingk. 2' => 'Tingk. 2',
            'Tingk. 3' => 'Tingk. 3',
            'Tingk. 4' => 'Tingk. 4',
            'Tingk. 5' => 'Tingk. 5'
        ];
    } elseif ($educationLevel === 'Sekolah Rendah') {
        return [
            'Tahun 1' => 'Tahun 1',
            'Tahun 2' => 'Tahun 2',
            'Tahun 3' => 'Tahun 3',
            'Tahun 4' => 'Tahun 4',
            'Tahun 5' => 'Tahun 5',
            'Tahun 6' => 'Tahun 6'
        ];
    }
    return [];
}

/**
 * Generate Username from Full Name
 */
function generateUsername($fullName) {
    // Remove special characters, lowercase, replace spaces with nothing
    $username = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $fullName));
    // Add random suffix to ensure uniqueness
    $username .= rand(100, 999);
    return $username;
}

/**
 * Sanitize Output
 */
function h($string) {
    return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}

/**
 * JSON Response Helper
 */
function jsonResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

/**
 * Check if User is Logged In
 */
function requireLogin($redirectUrl = 'index.php') {
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type'])) {
        header("Location: $redirectUrl");
        exit;
    }
}

/**
 * Check User Role
 */
function requireRole($allowedRoles = [], $redirectUrl = 'index.php') {
    requireLogin($redirectUrl);
    if (!in_array($_SESSION['user_type'], $allowedRoles)) {
        header("Location: $redirectUrl");
        exit;
    }
}

