<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\RESTful\ResourceController;

class AppVersion extends ResourceController
{
    use ResponseTrait;
    
    protected $format = 'json';

    /**
     * Get current app version and download links
     * GET /api/app-version
     * 
     * Returns the current app version number and download links for various app stores
     * 
     * @return \CodeIgniter\HTTP\Response
     */
    public function index()
    {
        try {
            $db = \Config\Database::connect();
            
            // Debug: Check if table exists
            $tableExists = $db->tableExists('app_settings');
            log_message('debug', 'AppVersion: Table exists: ' . ($tableExists ? 'YES' : 'NO'));
            
            // Get version from database or use default
            $version = $this->getAppVersion();
            $downloadLinks = $this->getDownloadLinks();
            
            // Debug logging
            log_message('debug', 'AppVersion: Version = ' . $version);
            log_message('debug', 'AppVersion: Download links = ' . json_encode($downloadLinks));
            
            // Debug: Query all app_settings
            if ($tableExists) {
                $allSettings = $db->table('app_settings')->get()->getResultArray();
                log_message('debug', 'AppVersion: All settings = ' . json_encode($allSettings));
            }

            return $this->respond([
                'version' => (int) $version,
                'downloadLinks' => $downloadLinks,
                'requireUpdateAndroid' => $this->getRequireUpdateFlag($db, 'require_update_android'),
                'requireUpdateIos' => $this->getRequireUpdateFlag($db, 'require_update_ios'),
                'debug' => [
                    'tableExists' => $tableExists,
                    'allSettings' => $tableExists ? $db->table('app_settings')->get()->getResultArray() : []
                ]
            ]);
        } catch (\Exception $e) {
            log_message('error', 'AppVersion::index error: ' . $e->getMessage());
            log_message('error', 'AppVersion::index stack trace: ' . $e->getTraceAsString());
            return $this->fail('Failed to retrieve app version information: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get the current app version from database or config
     * 
     * @return int
     */
    private function getAppVersion()
    {
        $db = \Config\Database::connect();
        
        // Check if app_settings table exists and has version
        if ($db->tableExists('app_settings')) {
            $result = $db->table('app_settings')
                ->where('setting_key', 'app_version')
                ->get()
                ->getRowArray();
            
            log_message('debug', 'AppVersion::getAppVersion - Query result: ' . json_encode($result));
            
            if ($result && isset($result['setting_value'])) {
                $version = (int) $result['setting_value'];
                log_message('debug', 'AppVersion::getAppVersion - Found version: ' . $version);
                return $version;
            } else {
                log_message('debug', 'AppVersion::getAppVersion - No version found in database');
            }
        } else {
            log_message('debug', 'AppVersion::getAppVersion - Table does not exist');
        }
        
        // Default version if not found in database
        log_message('debug', 'AppVersion::getAppVersion - Using default version: 1');
        return 1;
    }

    /**
     * Whether this platform should show a forced update when version is behind.
     * Missing row or unknown value defaults to true (backward compatible).
     */
    private function getRequireUpdateFlag($db, string $key): bool
    {
        if (!$db->tableExists('app_settings')) {
            return true;
        }
        $result = $db->table('app_settings')
            ->where('setting_key', $key)
            ->get()
            ->getRowArray();
        if (!$result || !isset($result['setting_value'])) {
            return true;
        }
        $v = strtolower(trim((string) $result['setting_value']));
        if (in_array($v, ['0', 'false', 'no', 'off'], true)) {
            return false;
        }
        return true;
    }

    /**
     * Get download links from database or config
     * Only returns links that are not NULL or empty
     * 
     * @return array
     */
    private function getDownloadLinks()
    {
        $db = \Config\Database::connect();
        $links = [];
        
        // Check if app_settings table exists
        if ($db->tableExists('app_settings')) {
            $results = $db->table('app_settings')
                ->where('setting_key LIKE', 'download_link_%')
                ->get()
                ->getResultArray();
            
            log_message('debug', 'AppVersion::getDownloadLinks - Found ' . count($results) . ' download links');
            
            foreach ($results as $row) {
                $key = str_replace('download_link_', '', $row['setting_key']);
                $value = $row['setting_value'];
                
                // Only include non-empty, non-null values
                if (!empty($value) && $value !== null && trim($value) !== '') {
                    $links[$key] = $value;
                    log_message('debug', "AppVersion::getDownloadLinks - Link: $key = " . $value);
                } else {
                    log_message('debug', "AppVersion::getDownloadLinks - Skipping empty/null link: $key");
                }
            }
        } else {
            log_message('debug', 'AppVersion::getDownloadLinks - Table does not exist');
        }
        
        // If no links found in database, return empty array
        // Admin can add links via database or update this method
        return $links;
    }

    /**
     * Update app version (Admin only - can be called via POST)
     * POST /api/app-version/update
     * Body: { "version": 2, "downloadLinks": { "apk": "...", "googlePlay": "..." } }
     * 
     * @return \CodeIgniter\HTTP\Response
     */
    public function updateVersion()
    {
        // TODO: Add authentication/authorization check here
        // For now, this is a simple implementation
        
        $requestData = $this->request->getJSON(true);
        
        if (!isset($requestData['version'])) {
            return $this->fail('Version is required', 400);
        }
        
        $db = \Config\Database::connect();
        
        // Create app_settings table if it doesn't exist
        $this->ensureAppSettingsTable($db);
        
        // Update version
        $version = (int) $requestData['version'];
        $this->updateSetting($db, 'app_version', $version);

        if (array_key_exists('requireUpdateAndroid', $requestData)) {
            $this->updateSetting(
                $db,
                'require_update_android',
                $this->jsonBoolToFlag($requestData['requireUpdateAndroid']) ? '1' : '0'
            );
        }
        if (array_key_exists('requireUpdateIos', $requestData)) {
            $this->updateSetting(
                $db,
                'require_update_ios',
                $this->jsonBoolToFlag($requestData['requireUpdateIos']) ? '1' : '0'
            );
        }
        
        // Update download links
        if (isset($requestData['downloadLinks']) && is_array($requestData['downloadLinks'])) {
            foreach ($requestData['downloadLinks'] as $key => $url) {
                $this->updateSetting($db, 'download_link_' . $key, $url);
            }
        }
        
        return $this->respond([
            'success' => true,
            'message' => 'App version updated successfully'
        ]);
    }

    /**
     * Ensure app_settings table exists
     * 
     * @param \CodeIgniter\Database\BaseConnection $db
     * @return void
     */
    private function ensureAppSettingsTable($db)
    {
        if (!$db->tableExists('app_settings')) {
            $sql = "CREATE TABLE IF NOT EXISTS `app_settings` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `setting_key` varchar(100) NOT NULL,
                `setting_value` text,
                `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                UNIQUE KEY `setting_key` (`setting_key`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";
            
            $db->query($sql);
        }
    }

    /**
     * Update or insert a setting
     * 
     * @param \CodeIgniter\Database\BaseConnection $db
     * @param string $key
     * @param mixed $value
     * @return bool
     */
    private function updateSetting($db, $key, $value)
    {
        $exists = $db->table('app_settings')
            ->where('setting_key', $key)
            ->countAllResults() > 0;
        
        if ($exists) {
            return $db->table('app_settings')
                ->where('setting_key', $key)
                ->update(['setting_value' => $value]);
        } else {
            return $db->table('app_settings')
                ->insert([
                    'setting_key' => $key,
                    'setting_value' => $value
                ]);
        }
    }

    /**
     * @param mixed $value JSON bool, int 0/1, or string
     */
    private function jsonBoolToFlag($value): bool
    {
        if (is_bool($value)) {
            return $value;
        }
        if (is_int($value)) {
            return $value !== 0;
        }
        if (is_string($value)) {
            $v = strtolower(trim($value));
            if (in_array($v, ['0', 'false', 'no', 'off'], true)) {
                return false;
            }
        }
        return (bool) $value;
    }
}
