<!DOCTYPE html>
<html>
<head>
<?php include"comman/code_css.php"; ?>
<style>
.cron-command-box {
    background: #f8f9fa;
    color: #212529;
    padding: 15px 15px;
    border-radius: 4px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 13px;
    overflow-x: auto;
    position: relative;
    margin-bottom: 10px;
    border: 2px solid #007bff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.cron-command-box code {
    color: #d63384;
    word-break: break-all;
    white-space: pre-wrap;
    display: block;
    padding-right: 70px;
    font-weight: 600;
    line-height: 1.6;
    font-size: 13px;
}
.copy-btn {
    position: absolute;
    top: 8px;
    right: 8px;
    background: #007bff;
    color: white;
    border: none;
    padding: 5px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 11px;
    font-weight: 600;
    box-shadow: 0 1px 3px rgba(0,0,0,0.2);
    transition: all 0.2s;
}
.copy-btn:hover { 
    background: #0056b3; 
    transform: translateY(-1px);
    box-shadow: 0 2px 5px rgba(0,0,0,0.3);
}
.copy-btn.copied { 
    background: #28a745; 
    border-color: #28a745;
}
.env-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 10px;
    font-weight: 600;
    margin-right: 3px;
    background: #27ae60;
    color: white;
}
.recommended-tag {
    background: #27ae60;
    color: white;
    padding: 2px 6px;
    border-radius: 8px;
    font-size: 9px;
    margin-left: 5px;
}
.panel-heading { 
    padding: 10px 15px !important; 
    font-size: 14px !important; 
    font-weight: 600 !important;
}
.panel-body { 
    padding: 12px 15px !important; 
}
.panel-body p { 
    font-size: 12px; 
    margin-bottom: 10px; 
    color: #495057; 
    font-weight: 500;
}
.box-title { font-size: 13px !important; }
.box-header { padding: 6px 10px !important; }
.box-body { padding: 8px !important; }
.content-header h1 { font-size: 16px !important; }
ol, ul { padding-left: 18px; font-size: 11px; margin-bottom: 5px; }
ol li, ul li { margin-bottom: 3px; }
.stat-card {
    background: #fff;
    border-radius: 4px;
    padding: 12px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    margin-bottom: 10px;
}
.stat-card .icon { font-size: 20px; margin-bottom: 5px; }
.stat-card .label { font-size: 10px; color: #666; text-transform: uppercase; }
.stat-card .value { font-size: 14px; font-weight: bold; }
.stat-card.green { border-left: 3px solid #27ae60; }
.stat-card.blue { border-left: 3px solid #3498db; }
.stat-card.purple { border-left: 3px solid #9b59b6; }
</style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php include"sidebar.php"; ?>

<div class="content-wrapper">
    <section class="content-header" style="padding: 8px 15px;">
        <h1><i class="fa fa-clock-o"></i> <?= $page_title ?></h1>
    </section>

    <section class="content" style="padding: 8px;">
        <?php include"comman/code_flashdata.php"; ?>

        <div class="row">
            <!-- Left Column - Stats & Actions -->
            <div class="col-md-3">
                <!-- Quick Stats -->
                <div class="stat-card green">
                    <div class="icon text-success"><i class="fa fa-database"></i></div>
                    <div class="value"><?= $backup_status['total_backups'] ?? 0 ?></div>
                    <div class="label">Total Backups</div>
                </div>
                <div class="stat-card blue">
                    <div class="icon text-primary"><i class="fa fa-<?= $server_info['is_windows'] ? 'windows' : 'linux' ?>"></i></div>
                    <div class="value"><?= $server_info['is_windows'] ? 'Windows' : 'Linux' ?></div>
                    <div class="label">Server OS</div>
                </div>
                <div class="stat-card purple">
                    <div class="icon" style="color:#9b59b6;"><i class="fa fa-check-circle"></i></div>
                    <div class="value"><?= ($backup_status['directory_writable'] ?? false) ? 'Ready' : 'Error' ?></div>
                    <div class="label">Status</div>
                </div>
                <?php if (!empty($backup_status['total_size'])): ?>
                <div class="stat-card" style="border-left:3px solid #f39c12;">
                    <div class="icon" style="color:#f39c12;"><i class="fa fa-hdd-o"></i></div>
                    <div class="value"><?= $backup_status['total_size'] ?></div>
                    <div class="label">Total Size</div>
                </div>
                <?php endif; ?>

                <!-- Quick Actions -->
                <div class="box box-success" style="margin-top:5px;">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-bolt"></i> Actions</h3>
                    </div>
                    <div class="box-body">
                        <button type="button" class="btn btn-primary btn-sm btn-block" data-toggle="modal" data-target="#backupModal">
                            <i class="fa fa-download"></i> Backup Now
                        </button>
                        <button type="button" class="btn btn-info btn-sm btn-block" id="testCronBtn">
                            <i class="fa fa-check-circle"></i> Test Setup
                        </button>
                        <a href="<?= base_url('backup') ?>" class="btn btn-default btn-sm btn-block">
                            <i class="fa fa-database"></i> View Backups
                        </a>
                    </div>
                </div>
                
                <!-- Backup Info -->
                <?php if (!empty($backup_status['latest_backup']) && $backup_status['latest_backup'] !== 'None'): ?>
                <div class="box box-info" style="margin-top:5px;">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-info-circle"></i> Latest Backup</h3>
                    </div>
                    <div class="box-body" style="font-size:11px;">
                        <p><strong>File:</strong> <?= htmlspecialchars($backup_status['latest_backup']) ?></p>
                        <p><strong>Date:</strong> <?= $backup_status['latest_backup_date'] ?></p>
                        <p><strong>Size:</strong> <?= $backup_status['latest_backup_size'] ?></p>
                        <p><strong>Age:</strong> <?= $backup_status['latest_backup_age'] ?? 'N/A' ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Detected Environment -->
                <div class="box box-default">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-server"></i> Detected</h3>
                    </div>
                    <div class="box-body" style="font-size:11px;">
                        <?php if($server_info['is_cpanel']): ?><span class="env-badge">cPanel</span><?php endif; ?>
                        <?php if($server_info['is_xampp']): ?><span class="env-badge">XAMPP</span><?php endif; ?>
                        <?php if($server_info['is_localhost']): ?><span class="env-badge">Localhost</span><?php endif; ?>
                        <?php if($server_info['is_windows']): ?><span class="env-badge">Windows</span><?php endif; ?>
                        <?php if($server_info['is_linux']): ?><span class="env-badge">Linux</span><?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Right Column - Cron Commands -->
            <div class="col-md-9">
                <div class="box box-warning">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-terminal"></i> Cron Commands</h3>
                    </div>
                    <div class="box-body">
                        <?php
                        // Determine recommended
                        $recommended = 'linux_daily';
                        if ($server_info['is_cpanel']) $recommended = 'cpanel';
                        elseif ($server_info['is_windows']) $recommended = 'windows';
                        elseif ($server_info['is_localhost'] && $server_info['is_xampp']) $recommended = 'windows';

                        // Show only relevant commands
                        $show_commands = array();
                        if ($server_info['is_windows']) {
                            $show_commands = array('windows', 'web_url');
                        } elseif ($server_info['is_cpanel']) {
                            $show_commands = array('cpanel', 'linux_daily', 'web_url');
                        } else {
                            $show_commands = array('linux_daily', 'curl', 'web_url');
                        }
                        ?>

                        <?php foreach ($cron_commands as $key => $cmd): ?>
                        <?php if (!in_array($key, $show_commands)) continue; ?>
                        <div class="panel panel-<?= ($key == $recommended) ? 'success' : 'default' ?>" style="margin-bottom:15px;border:1px solid #dee2e6;">
                            <div class="panel-heading" style="<?= ($key == $recommended) ? 'background:#d4edda;border-bottom:2px solid #28a745;' : 'background:#f8f9fa;border-bottom:1px solid #dee2e6;' ?>">
                                <strong style="font-size:15px;"><?= $cmd['title'] ?></strong>
                                <?php if ($key == $recommended): ?><span class="recommended-tag" style="font-size:10px;padding:3px 8px;">RECOMMENDED</span><?php endif; ?>
                            </div>
                            <div class="panel-body" style="background:#fff;">
                                <p style="margin-bottom:12px;color:#495057;font-size:13px;"><strong><?= $cmd['description'] ?></strong></p>
                                <div class="cron-command-box" id="cmd-<?= $key ?>">
                                    <button class="copy-btn" onclick="copyCmd('<?= $key ?>')" title="Copy to clipboard"><i class="fa fa-copy"></i> Copy</button>
                                    <code><?= htmlspecialchars($cmd['command']) ?></code>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Setup Instructions -->
                <div class="box box-info">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-<?= $server_info['is_windows'] ? 'windows' : 'linux' ?>"></i>
                            <?= $server_info['is_windows'] ? 'Windows Task Scheduler' : 'cPanel / Linux Setup' ?>
                        </h3>
                    </div>
                    <div class="box-body">
                        <?php if ($server_info['is_windows']): ?>
                        <ol>
                            <li>Open <strong>Task Scheduler</strong> (search in Start menu)</li>
                            <li>Click <strong>Create Basic Task</strong></li>
                            <li>Name: "NCS Billing Backup", Trigger: <strong>Daily</strong> at 2:00 AM</li>
                            <li>Action: <strong>Start a program</strong></li>
                            <li>Program: <code style="font-size:10px;background:#eee;padding:2px 5px;"><?= htmlspecialchars($server_info['php_binary']) ?></code></li>
                            <li>Arguments: <code style="font-size:10px;background:#eee;padding:2px 5px;"><?= htmlspecialchars($server_info['index_file']) ?> cron run</code></li>
                        </ol>
                        <?php else: ?>
                        <ol>
                            <li>Login to cPanel → Go to <strong>Cron Jobs</strong></li>
                            <li>Set time: <code style="background:#eee;padding:2px 5px;">0 2 * * *</code> (Daily at 2 AM)</li>
                            <li>Paste the recommended command above</li>
                            <li>Click <strong>Add New Cron Job</strong></li>
                        </ol>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Cron Log -->
                <?php if ($backup_status['cron_log_exists'] && !empty($backup_status['last_cron_entries'])): ?>
                <div class="box box-default">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-file-text-o"></i> Recent Cron Activity</h3>
                    </div>
                    <div class="box-body" style="max-height:200px;overflow-y:auto;font-size:10px;font-family:monospace;background:#f5f5f5;padding:8px;">
                        <?php foreach (array_reverse($backup_status['last_cron_entries']) as $entry): ?>
                            <div style="margin-bottom:3px;color:#666;"><?= htmlspecialchars(trim($entry)) ?></div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- System Information -->
                <div class="box box-default">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-server"></i> System Information</h3>
                    </div>
                    <div class="box-body" style="font-size:11px;">
                        <p><strong>PHP Version:</strong> <?= PHP_VERSION ?></p>
                        <p><strong>PHP Binary:</strong> <code style="font-size:9px;background:#eee;padding:2px 4px;"><?= htmlspecialchars($server_info['php_binary']) ?></code></p>
                        <p><strong>Application Path:</strong> <code style="font-size:9px;background:#eee;padding:2px 4px;"><?= htmlspecialchars($server_info['app_path']) ?></code></p>
                        <?php if (!empty($server_info['secret_key'])): ?>
                        <p><strong>Cron Secret Key:</strong> <code style="font-size:9px;background:#eee;padding:2px 4px;"><?= htmlspecialchars($server_info['secret_key']) ?></code></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

    </section>
</div>

<!-- Backup Confirmation Modal -->
<div class="modal fade" id="backupModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                <h4 class="modal-title"><i class="fa fa-database"></i> Create Backup</h4>
            </div>
            <div class="modal-body text-center">
                <i class="fa fa-question-circle fa-3x text-primary" style="margin-bottom:10px;"></i>
                <p>Create a new database backup now?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Cancel</button>
                <a href="<?= base_url('cron_setup/run_backup') ?>" class="btn btn-primary btn-sm"><i class="fa fa-check"></i> Yes, Backup</a>
            </div>
        </div>
    </div>
</div>

<?php include"footer.php"; ?>
</div>

<?php include"comman/code_js.php"; ?>

<script>
function copyCmd(key) {
    var box = document.getElementById('cmd-' + key);
    var code = box.querySelector('code');
    var text = code.textContent || code.innerText;

    var textarea = document.createElement('textarea');
    textarea.value = text.trim();
    document.body.appendChild(textarea);
    textarea.select();
    
    try {
        document.execCommand('copy');
        var btn = box.querySelector('.copy-btn');
        btn.innerHTML = '<i class="fa fa-check"></i> Copied!';
        btn.classList.add('copied');

        setTimeout(function() {
            btn.innerHTML = '<i class="fa fa-copy"></i> Copy';
            btn.classList.remove('copied');
        }, 3000);
    } catch (err) {
        alert('Failed to copy. Please select and copy manually.');
    }
    
    document.body.removeChild(textarea);
}

// Test Cron Setup
$(document).ready(function() {
    $('#testCronBtn').on('click', function() {
        var btn = $(this);
        var originalText = btn.html();
        
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
        
        $.ajax({
            url: '<?= base_url("cron_setup/test_cron") ?>',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                btn.prop('disabled', false).html(originalText);
                
                var icon = response.success ? 'success' : 'error';
                var title = response.success ? 'Test Passed!' : 'Test Failed';
                
                // Build the message
                var messageHtml = '';
                
                if (response.success) {
                    messageHtml = '<div style="text-align:center;padding:10px 0;">';
                    messageHtml += '<div style="font-size:48px;color:#28a745;margin-bottom:15px;"><i class="fa fa-check-circle"></i></div>';
                    messageHtml += '<h4 style="color:#28a745;margin-bottom:15px;font-weight:600;">All Tests Passed!</h4>';
                    messageHtml += '<p style="font-size:14px;color:#495057;margin-bottom:20px;">Your cron setup is ready. All required components are properly configured.</p>';
                    messageHtml += '</div>';
                } else {
                    messageHtml = '<div style="text-align:center;padding:10px 0;">';
                    messageHtml += '<div style="font-size:48px;color:#dc3545;margin-bottom:15px;"><i class="fa fa-times-circle"></i></div>';
                    messageHtml += '<h4 style="color:#dc3545;margin-bottom:15px;font-weight:600;">Test Failed</h4>';
                    if (response.message && response.message.indexOf('Warning') === -1) {
                        messageHtml += '<p style="font-size:14px;color:#495057;margin-bottom:20px;">' + response.message + '</p>';
                    }
                    messageHtml += '</div>';
                }
                
                // Show detailed results in a nice table
                var detailsHtml = '';
                if (response.details) {
                    detailsHtml = '<div style="text-align:left;margin-top:20px;border-top:1px solid #dee2e6;padding-top:15px;">';
                    detailsHtml += '<h5 style="font-size:13px;margin-bottom:10px;color:#495057;"><i class="fa fa-info-circle"></i> Test Details:</h5>';
                    detailsHtml += '<div style="max-height:300px;overflow-y:auto;">';
                    detailsHtml += '<table class="table table-bordered table-sm" style="font-size:12px;margin-bottom:0;">';
                    detailsHtml += '<thead style="background:#f8f9fa;"><tr><th style="width:40%;padding:8px;">Check</th><th style="padding:8px;">Result</th></tr></thead>';
                    detailsHtml += '<tbody>';
                    
                    // Format field names nicely
                    var fieldLabels = {
                        'php_binary': 'PHP Binary Path',
                        'php_binary_exists': 'PHP Binary Exists',
                        'php_binary_valid': 'PHP Binary Valid',
                        'index_file': 'Index File Path',
                        'index_file_exists': 'Index File Exists',
                        'backup_directory': 'Backup Directory',
                        'backup_dir_exists': 'Backup Directory Exists',
                        'backup_dir_writable': 'Backup Directory Writable',
                        'database_connected': 'Database Connected',
                        'cron_url': 'Cron URL'
                    };
                    
                    for (var key in response.details) {
                        var value = response.details[key];
                        var label = fieldLabels[key] || key.replace(/_/g, ' ').replace(/\b\w/g, function(l) { return l.toUpperCase(); });
                        
                        var displayValue = '';
                        if (typeof value === 'boolean') {
                            if (value) {
                                displayValue = '<span class="text-success"><i class="fa fa-check-circle"></i> Yes</span>';
                            } else {
                                displayValue = '<span class="text-danger"><i class="fa fa-times-circle"></i> No</span>';
                            }
                        } else if (key === 'cron_url' || key === 'php_binary' || key === 'index_file' || key === 'backup_directory') {
                            // For paths and URLs, show in a code-like format
                            displayValue = '<code style="background:#f8f9fa;padding:2px 6px;border-radius:3px;font-size:11px;word-break:break-all;">' + value + '</code>';
                        } else {
                            displayValue = value;
                        }
                        
                        detailsHtml += '<tr><td style="padding:8px;"><strong>' + label + '</strong></td><td style="padding:8px;">' + displayValue + '</td></tr>';
                    }
                    detailsHtml += '</tbody></table>';
                    detailsHtml += '</div>';
                    detailsHtml += '</div>';
                }
                
                // Combine message and details
                var fullMessage = messageHtml + detailsHtml;
                
                // Use SweetAlert if available, otherwise use alert
                if (typeof swal !== 'undefined') {
                    swal({
                        title: title,
                        html: fullMessage,
                        type: icon,
                        width: '600px',
                        confirmButtonText: 'OK',
                        confirmButtonClass: 'btn btn-primary'
                    });
                } else {
                    alert(title + '\n\n' + (response.message || 'Test completed'));
                    console.log('Test Details:', response.details);
                }
            },
            error: function(xhr, status, error) {
                btn.prop('disabled', false).html(originalText);
                if (typeof swal !== 'undefined') {
                    swal({
                        title: 'Error',
                        text: 'Failed to run test. Please try again.',
                        type: 'error',
                        confirmButtonText: 'OK'
                    });
                } else {
                    alert('Error: Failed to run test. Please try again.');
                }
            }
        });
    });
    
    // Show loading state for backup button
    $('#backupModal').on('show.bs.modal', function() {
        // Modal is opening
    });
});
</script>

<script>$(".cron-setup-active-li").addClass("active");</script>
</body>
</html>
