<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * System Settings Dashboard
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('settings.view');

// Set page title
$page_title = 'System Settings';

// Get current user
$current_user = current_user();

// Get system information
$system_info = [
    'php_version' => phpversion(),
    'mysql_version' => db_fetch_value("SELECT VERSION()"),
    'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
    'server_os' => PHP_OS,
    'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown',
    'base_path' => BASE_PATH,
    'max_upload_size' => ini_get('upload_max_filesize'),
    'max_post_size' => ini_get('post_max_size'),
    'memory_limit' => ini_get('memory_limit'),
    'max_execution_time' => ini_get('max_execution_time'),
    'session_save_path' => session_save_path() ?: 'Default',
    'timezone' => date_default_timezone_get(),
    'date' => date(DATETIME_FORMAT)
];

// Get application settings
$settings = [];
$settings_data = db_fetch_all("SELECT * FROM system_settings ORDER BY setting_key");
foreach ($settings_data as $row) {
    $settings[$row['setting_key']] = $row;
}

// Get resort settings
$resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1");

// Get counts for various settings
$counts = [
    'users' => db_count('users'),
    'roles' => db_count('roles'),
    'permissions' => db_count('permissions'),
    'tax_rates' => db_count('tax_rates'),
    'currencies' => db_count('currency_rates'),
    'outlets' => db_count('pos_outlets'),
    'payment_methods' => db_count('payment_methods'),
    'email_templates' => db_count('notification_templates', "template_type = 'email'")
];

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.php';
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">System Settings</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item active">Settings</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Settings Categories -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/settings/resort.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3>Resort</h3>
                            <p>Basic Information</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-hotel"></i>
                        </div>
                        <div class="small-box-footer">
                            Configure <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
            
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/settings/tax-currency.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3><?php echo $counts['tax_rates']; ?> Tax</h3>
                            <p><?php echo $counts['currencies']; ?> Currencies</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-percent"></i>
                        </div>
                        <div class="small-box-footer">
                            Configure <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
            
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/settings/outlets.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3><?php echo $counts['outlets']; ?> Outlets</h3>
                            <p>POS Locations</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-store"></i>
                        </div>
                        <div class="small-box-footer">
                            Configure <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
            
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/settings/payment-methods.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3><?php echo $counts['payment_methods']; ?> Methods</h3>
                            <p>Payment Options</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-credit-card"></i>
                        </div>
                        <div class="small-box-footer">
                            Configure <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/settings/email-sms.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-primary">
                        <div class="inner">
                            <h3><?php echo $counts['email_templates']; ?> Templates</h3>
                            <p>Email & SMS</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-envelope"></i>
                        </div>
                        <div class="small-box-footer">
                            Configure <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
            
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/settings/backup-restore.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-secondary">
                        <div class="inner">
                            <h3>Backup</h3>
                            <p>& Restore</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-database"></i>
                        </div>
                        <div class="small-box-footer">
                            Configure <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
            
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/users/index.php'); ?>" class="small-box-footer">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3><?php echo $counts['users']; ?> Users</h3>
                            <p><?php echo $counts['roles']; ?> Roles</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-users-cog"></i>
                        </div>
                        <div class="small-box-footer">
                            Manage <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
            
            <div class="col-lg-3 col-6">
                <a href="<?php echo base_url('admin/users/permissions.php?role_id=1'); ?>" class="small-box-footer">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3><?php echo $counts['permissions']; ?> Permissions</h3>
                            <p>Access Control</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-key"></i>
                        </div>
                        <div class="small-box-footer">
                            Manage <i class="fas fa-arrow-circle-right"></i>
                        </div>
                    </div>
                </a>
            </div>
        </div>

        <!-- Resort Information Card -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle mr-1"></i>
                            Resort Information
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('admin/settings/resort.php'); ?>" class="btn btn-sm btn-primary">
                                <i class="fas fa-edit"></i> Edit
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if ($resort): ?>
                            <table class="table table-sm">
                                <tr>
                                    <th style="width: 150px;">Resort Name:</th>
                                    <td><?php echo escape_html($resort['resort_name']); ?></td>
                                </tr>
                                <tr>
                                    <th>Address:</th>
                                    <td><?php echo nl2br(escape_html($resort['resort_address'] ?? 'Not set')); ?></td>
                                </tr>
                                <tr>
                                    <th>City/State:</th>
                                    <td>
                                        <?php 
                                        $parts = array_filter([
                                            $resort['resort_city'] ?? '',
                                            $resort['resort_state'] ?? '',
                                            $resort['resort_country'] ?? ''
                                        ]);
                                        echo escape_html(implode(', ', $parts)) ?: 'Not set';
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Phone:</th>
                                    <td><?php echo escape_html($resort['resort_phone'] ?? 'Not set'); ?></td>
                                </tr>
                                <tr>
                                    <th>Email:</th>
                                    <td><?php echo escape_html($resort['resort_email'] ?? 'Not set'); ?></td>
                                </tr>
                                <tr>
                                    <th>Website:</th>
                                    <td>
                                        <?php if (!empty($resort['resort_website'])): ?>
                                            <a href="<?php echo escape_html($resort['resort_website']); ?>" target="_blank">
                                                <?php echo escape_html($resort['resort_website']); ?>
                                            </a>
                                        <?php else: ?>
                                            Not set
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Check-in/out:</th>
                                    <td>
                                        <?php echo substr($resort['checkin_time'] ?? DEFAULT_CHECKIN_TIME, 0, 5); ?> / 
                                        <?php echo substr($resort['checkout_time'] ?? DEFAULT_CHECKOUT_TIME, 0, 5); ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Default Currency:</th>
                                    <td><?php echo escape_html($resort['default_currency'] ?? DEFAULT_CURRENCY); ?></td>
                                </tr>
                                <tr>
                                    <th>Timezone:</th>
                                    <td><?php echo escape_html($resort['timezone'] ?? DEFAULT_TIMEZONE); ?></td>
                                </tr>
                            </table>
                        <?php else: ?>
                            <div class="text-center text-muted py-3">
                                <i class="fas fa-hotel fa-3x mb-3"></i>
                                <p>Resort information not configured yet.</p>
                                <a href="<?php echo base_url('admin/settings/resort.php'); ?>" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Configure Resort
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- System Information Card -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-server mr-1"></i>
                            System Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 150px;">Application:</th>
                                <td><?php echo APP_NAME; ?> v<?php echo APP_VERSION; ?></td>
                            </tr>
                            <tr>
                                <th>PHP Version:</th>
                                <td><?php echo $system_info['php_version']; ?></td>
                            </tr>
                            <tr>
                                <th>MySQL Version:</th>
                                <td><?php echo $system_info['mysql_version']; ?></td>
                            </tr>
                            <tr>
                                <th>Server:</th>
                                <td><?php echo escape_html($system_info['server_software']); ?></td>
                            </tr>
                            <tr>
                                <th>Operating System:</th>
                                <td><?php echo $system_info['server_os']; ?></td>
                            </tr>
                            <tr>
                                <th>Base Path:</th>
                                <td><code><?php echo $system_info['base_path']; ?></code></td>
                            </tr>
                            <tr>
                                <th>Document Root:</th>
                                <td><code><?php echo escape_html($system_info['document_root']); ?></code></td>
                            </tr>
                            <tr>
                                <th>Upload Max Size:</th>
                                <td><?php echo $system_info['max_upload_size']; ?></td>
                            </tr>
                            <tr>
                                <th>Memory Limit:</th>
                                <td><?php echo $system_info['memory_limit']; ?></td>
                            </tr>
                            <tr>
                                <th>Max Execution Time:</th>
                                <td><?php echo $system_info['max_execution_time']; ?>s</td>
                            </tr>
                            <tr>
                                <th>Timezone:</th>
                                <td><?php echo $system_info['timezone']; ?></td>
                            </tr>
                            <tr>
                                <th>Current Time:</th>
                                <td><?php echo $system_info['date']; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-bolt mr-1"></i>
                            Quick Actions
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="btn-group flex-wrap">
                            <button type="button" class="btn btn-default" onclick="clearSystemCache()">
                                <i class="fas fa-trash-alt mr-1"></i> Clear Cache
                            </button>
                            <button type="button" class="btn btn-default" onclick="optimizeDatabase()">
                                <i class="fas fa-database mr-1"></i> Optimize DB
                            </button>
                            <button type="button" class="btn btn-default" onclick="testEmailConfig()">
                                <i class="fas fa-envelope mr-1"></i> Test Email
                            </button>
                            <button type="button" class="btn btn-default" onclick="viewErrorLogs()">
                                <i class="fas fa-exclamation-triangle mr-1"></i> Error Logs
                            </button>
                            <button type="button" class="btn btn-default" onclick="phpInfo()">
                                <i class="fas fa-info-circle mr-1"></i> PHP Info
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function clearSystemCache() {
    if (confirm('Clear system cache? This may temporarily affect performance.')) {
        $.post('<?php echo base_url('api/clear-cache.php'); ?>', {
            csrf_token: '<?php echo csrf_token(); ?>'
        }, function(response) {
            if (response.status === 'success') {
                alert('Cache cleared successfully');
            } else {
                alert('Failed to clear cache: ' + response.message);
            }
        }).fail(function() {
            alert('Failed to clear cache');
        });
    }
}

function optimizeDatabase() {
    if (confirm('Optimize database tables? This may take a few moments.')) {
        $.post('<?php echo base_url('api/optimize-db.php'); ?>', {
            csrf_token: '<?php echo csrf_token(); ?>'
        }, function(response) {
            if (response.status === 'success') {
                alert('Database optimized successfully');
            } else {
                alert('Failed to optimize database: ' + response.message);
            }
        }).fail(function() {
            alert('Failed to optimize database');
        });
    }
}

function testEmailConfig() {
    const email = prompt('Enter email address to send test message:');
    if (email) {
        $.post('<?php echo base_url('api/test-email.php'); ?>', {
            email: email,
            csrf_token: '<?php echo csrf_token(); ?>'
        }, function(response) {
            if (response.status === 'success') {
                alert('Test email sent successfully');
            } else {
                alert('Failed to send test email: ' + response.message);
            }
        }).fail(function() {
            alert('Failed to send test email');
        });
    }
}

function viewErrorLogs() {
    window.open('<?php echo base_url('admin/settings/error-logs.php'); ?>', '_blank');
}

function phpInfo() {
    window.open('<?php echo base_url('api/phpinfo.php'); ?>', '_blank');
}
</script>

<style>
.small-box {
    cursor: pointer;
    transition: transform 0.3s ease;
}
.small-box:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.small-box a {
    color: inherit;
    text-decoration: none;
}
.small-box .small-box-footer {
    background: rgba(0,0,0,0.1);
    color: white;
    padding: 8px 0;
    text-align: center;
    display: block;
}
.btn-group .btn {
    margin: 0 2px;
}
</style>

<?php
// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>