<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index(): string
    {
        $db = \Config\Database::connect();
        $downloadLinks = [];
        
        // Fetch download links from database
        if ($db->tableExists('app_settings')) {
            try {
                // Get all download link settings from database
                $results = $db->table('app_settings')
                    ->like('setting_key', 'download_link_', 'after')
                    ->get()
                    ->getResultArray();
                
                foreach ($results as $row) {
                    $key = str_replace('download_link_', '', $row['setting_key']);
                    $value = $row['setting_value'];
                    
                    // Clean and validate the URL
                    if (!empty($value) && 
                        $value !== null && 
                        trim($value) !== '' && 
                        trim($value) !== 'null') {
                        
                        $cleanUrl = trim($value);
                        
                        // Decode URL if it's already encoded (to prevent double encoding)
                        if (strpos($cleanUrl, '%') !== false) {
                            $cleanUrl = urldecode($cleanUrl);
                        }
                        
                        // Validate URL
                        if (filter_var($cleanUrl, FILTER_VALIDATE_URL) !== false) {
                            $downloadLinks[$key] = $cleanUrl;
                        }
                    }
                }
            } catch (\Exception $e) {
                // Log error but don't break the page
                log_message('error', 'Home::index - Error fetching download links: ' . $e->getMessage());
            }
        }
        
        $data = [
            'downloadLinks' => $downloadLinks
        ];
        
        return view('welcome_message', $data);
    }
}
