<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$page_title = 'App Version Manager';
$current_page = 'app_version_manager.php';

$pdo = getDBConnection();

$success_message = '';
$error_message = '';
$default_app_version = '1.10.7';
$default_app_build_number = '22';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_version'])) {
    try {
        $app_version = $_POST['app_version'] ?? '';
        $app_build_number = $_POST['app_build_number'] ?? '';
        $force_update = $_POST['force_update'] ?? '0';
        $update_message = $_POST['update_message'] ?? '';
        $update_url = $_POST['update_url'] ?? '';
        
        // Validate inputs
        if (empty($app_version)) {
            throw new Exception('App version is required');
        }

        if ($app_build_number !== '' && (!ctype_digit((string)$app_build_number) || (int)$app_build_number <= 0)) {
            throw new Exception('Build number must be a positive number');
        }
        
        if (empty($update_message)) {
            throw new Exception('Update message is required');
        }
        
        if (empty($update_url)) {
            throw new Exception('Update URL is required');
        }
        
        // Update settings in database
        $settings = [
            'app_version' => $app_version,
            'app_build_number' => $app_build_number !== '' ? $app_build_number : $default_app_build_number,
            'force_update' => $force_update,
            'update_message' => $update_message,
            'update_url' => $update_url
        ];
        
        foreach ($settings as $key => $value) {
            $stmt = $pdo->prepare("
                INSERT INTO settings (setting_key, setting_value) 
                VALUES (?, ?) 
                ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
            ");
            $stmt->execute([$key, $value]);
        }
        
        $success_message = "App version settings updated successfully!";
        
    } catch (Exception $e) {
        $error_message = "Error: " . $e->getMessage();
    }
}

// Get current settings
$current_settings = [];
$stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('app_version', 'app_build_number', 'force_update', 'update_message', 'update_url')");
while ($row = $stmt->fetch()) {
    $current_settings[$row['setting_key']] = $row['setting_value'];
}

// Set default values
$configured_app_version = $current_settings['app_version'] ?? $default_app_version;
$app_version = version_compare($configured_app_version, $default_app_version, '<') ? $default_app_version : $configured_app_version;
$app_build_number = (string)max((int)($current_settings['app_build_number'] ?? 0), (int)$default_app_build_number);
$force_update = $current_settings['force_update'] ?? '0';
$update_message = $current_settings['update_message'] ?? 'A new version of the app is available. Please update to continue using all features.';
$update_url = $current_settings['update_url'] ?? 'https://play.google.com/store/apps/details?id=my.astrosidhi.guru';
?>

<?php ob_start(); ?>
    <style>
        .version-manager-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            transition: all 0.3s;
        }
        .form-control:focus, .form-select:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        .btn-update {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            border: none;
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-update:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
        }
        .btn-test {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-test:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
        }
        .current-version {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .test-result {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-top: 20px;
            border-left: 4px solid #007bff;
        }
    </style>

    <div class="version-manager-card">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0">
                <i class="fas fa-mobile-alt me-2"></i>App Version Manager
            </h4>
        </div>
        <div class="card-body">
            
            <?php if ($success_message) { ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php } ?>
            
            <?php if ($error_message) { ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php } ?>
            
            <!-- Current Version Display -->
            <div class="current-version">
                <h5 class="mb-2">
                    <i class="fas fa-info-circle me-2"></i>Current Settings
                </h5>
                <div class="row">
                    <div class="col-md-2">
                        <strong>App Version:</strong><br>
                        <span class="badge bg-light text-dark"><?php echo htmlspecialchars($app_version); ?></span>
                    </div>
                    <div class="col-md-2">
                        <strong>Build:</strong><br>
                        <span class="badge bg-light text-dark"><?php echo htmlspecialchars($app_build_number); ?></span>
                    </div>
                    <div class="col-md-2">
                        <strong>Force Update:</strong><br>
                        <span class="badge bg-<?php echo $force_update === '1' ? 'danger' : 'success'; ?>">
                            <?php echo $force_update === '1' ? 'YES' : 'NO'; ?>
                        </span>
                    </div>
                    <div class="col-md-6">
                        <strong>Update URL:</strong><br>
                        <small><?php echo htmlspecialchars($update_url); ?></small>
                    </div>
                </div>
            </div>
            
            <!-- Update Form -->
            <form method="POST" id="versionForm">
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label fw-bold">
                                <i class="fas fa-code-branch me-2"></i>App Version
                            </label>
                            <input type="text" name="app_version" class="form-control" 
                                   value="<?php echo htmlspecialchars($app_version); ?>" 
                                   placeholder="e.g., 1.10.7" required>
                            <small class="text-muted">Latest app version name</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label fw-bold">
                                <i class="fas fa-hashtag me-2"></i>Build Number
                            </label>
                            <input type="number" name="app_build_number" class="form-control"
                                   value="<?php echo htmlspecialchars($app_build_number); ?>"
                                   min="1" placeholder="21" required>
                            <small class="text-muted">Latest Android build number</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label fw-bold">
                                <i class="fas fa-exclamation-triangle me-2"></i>Force Update
                            </label>
                            <select name="force_update" class="form-select">
                                <option value="0" <?php echo $force_update === '0' ? 'selected' : ''; ?>>No - Optional Update</option>
                                <option value="1" <?php echo $force_update === '1' ? 'selected' : ''; ?>>Yes - Force Update</option>
                            </select>
                            <small class="text-muted">Force users to update the app</small>
                        </div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold">
                        <i class="fas fa-bell me-2"></i>Update Message
                    </label>
                    <textarea name="update_message" class="form-control" rows="3" 
                              placeholder="Message shown when update is required" required><?php echo htmlspecialchars($update_message); ?></textarea>
                    <small class="text-muted">Message displayed when app update is required</small>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold">
                        <i class="fas fa-link me-2"></i>Update URL
                    </label>
                    <input type="url" name="update_url" class="form-control" 
                           value="<?php echo htmlspecialchars($update_url); ?>" 
                           placeholder="https://play.google.com/store/apps/details?id=my.astrosidhi.guru" required>
                    <small class="text-muted">URL where users can download the latest version</small>
                </div>
                
                <div class="d-flex gap-2">
                    <button type="submit" name="update_version" class="btn btn-update text-white">
                        <i class="fas fa-save me-2"></i>Update Settings
                    </button>
                    <button type="button" class="btn btn-test text-white" onclick="testUpdate()">
                        <i class="fas fa-play me-2"></i>Test Update Check
                    </button>
                </div>
            </form>
            
            <!-- Test Results -->
            <div id="testResults" class="test-result" style="display: none;">
                <h6><i class="fas fa-flask me-2"></i>Test Results</h6>
                <div id="testContent"></div>
            </div>
            
            <!-- Instructions -->
            <div class="mt-4">
                <h6><i class="fas fa-info-circle me-2"></i>How to Use:</h6>
                <ol>
                    <li><strong>Set App Version:</strong> Enter the latest app version, for example 1.10.7</li>
                    <li><strong>Choose Force Update:</strong> Select "Yes" to force users to update</li>
                    <li><strong>Update Message:</strong> Write a clear message for users</li>
                    <li><strong>Update URL:</strong> Set the Play Store or download link</li>
                    <li><strong>Save Settings:</strong> Click "Update Settings" to save</li>
                    <li><strong>Test:</strong> Use "Test Update Check" to verify</li>
                </ol>
            </div>
        </div>
    </div>

    <script>
        function testUpdate() {
            const testResults = document.getElementById('testResults');
            const testContent = document.getElementById('testContent');
            
            testResults.style.display = 'block';
            testContent.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div>Testing update check...';
            
            // Simulate test with previous app version 1.10.6+21
            const testData = {
                current_version: '1.10.6',
                current_build_number: 21
            };
            
            fetch('../api/check_app_update.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(testData)
            })
            .then(response => response.json())
            .then(data => {
                let resultHtml = '<div class="row">';
                resultHtml += '<div class="col-md-6">';
                resultHtml += '<strong>Test Version:</strong> 1.10.6+21<br>';
                resultHtml += '<strong>Server Version:</strong> ' + (data.latest_version || 'N/A') + '+' + (data.latest_build_number || '') + '<br>';
                resultHtml += '<strong>Needs Update:</strong> ' + (data.needs_update ? '<span class="badge bg-warning">YES</span>' : '<span class="badge bg-success">NO</span>') + '<br>';
                resultHtml += '</div>';
                resultHtml += '<div class="col-md-6">';
                resultHtml += '<strong>Force Update:</strong> ' + (data.force_update ? '<span class="badge bg-danger">YES</span>' : '<span class="badge bg-info">NO</span>') + '<br>';
                resultHtml += '<strong>Update Message:</strong><br><small>' + (data.update_message || 'N/A') + '</small><br>';
                resultHtml += '</div>';
                resultHtml += '</div>';
                
                if (data.needs_update) {
                    resultHtml += '<div class="alert alert-warning mt-2"><i class="fas fa-exclamation-triangle me-2"></i>Update popup will show to users!</div>';
                } else {
                    resultHtml += '<div class="alert alert-info mt-2"><i class="fas fa-info-circle me-2"></i>No update needed. Set higher version to test.</div>';
                }
                
                testContent.innerHTML = resultHtml;
            })
            .catch(error => {
                testContent.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i>Error testing: ' + error.message + '</div>';
            });
        }
    </script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>
