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

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

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

// Set page title
$page_title = 'Admin Dashboard';

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

// Get system statistics
$stats = [
    'total_users' => db_count('users'),
    'active_users' => db_count('users', 'is_active = 1'),
    'total_roles' => db_count('roles'),
    'total_permissions' => db_count('permissions'),
    'today_logins' => db_count('audit_logs', 'action = ? AND DATE(created_at) = CURDATE()', ['login']),
    'failed_logins' => db_count('audit_logs', 'action = ? AND DATE(created_at) = CURDATE()', ['login_failed']),
    'system_logs' => db_count('audit_logs', 'DATE(created_at) = CURDATE()'),
    'database_size' => get_db_size()
];

// Get recent user registrations
$recent_users = db_fetch_all(
    "SELECT user_id, username, email, first_name, last_name, role_id, created_at, is_active 
     FROM users 
     ORDER BY created_at DESC 
     LIMIT 10"
);

// Get recent audit logs
$recent_audit = db_fetch_all(
    "SELECT a.*, u.username, u.first_name, u.last_name 
     FROM audit_logs a
     LEFT JOIN users u ON a.user_id = u.user_id
     ORDER BY a.created_at DESC 
     LIMIT 15"
);

// Get user activity chart data (last 7 days)
$activity_data = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $activity_data['labels'][] = date('D, M d', strtotime($date));
    $activity_data['logins'][] = db_count('audit_logs', 'action = ? AND DATE(created_at) = ?', ['login', $date]);
    $activity_data['actions'][] = db_count('audit_logs', 'action NOT IN (?, ?) AND DATE(created_at) = ?', ['login', 'logout', $date]);
}

// Get top active users
$top_users = db_fetch_all(
    "SELECT u.user_id, u.username, u.first_name, u.last_name, COUNT(*) as action_count
     FROM audit_logs a
     JOIN users u ON a.user_id = u.user_id
     WHERE a.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
     GROUP BY u.user_id
     ORDER BY action_count DESC
     LIMIT 10"
);

// Get system health checks
$health_checks = [
    'database' => test_db_connection(),
    'uploads_writable' => is_writable(UPLOAD_PATH),
    'logs_writable' => is_writable(LOGS_PATH),
    'mail_configured' => SMTP_HOST && SMTP_USER && SMTP_PASS,
    'session_path' => session_save_path() ? is_writable(session_save_path()) : true
];

// Include header
require_once dirname(__DIR__) . '/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">Admin Dashboard</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 active">Admin Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- System Health Alert -->
        <?php if (!$health_checks['database'] || !$health_checks['uploads_writable'] || !$health_checks['logs_writable']): ?>
        <div class="alert alert-warning alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            <strong>System Health Issues Detected:</strong>
            <ul class="mt-2 mb-0">
                <?php if (!$health_checks['database']): ?>
                    <li>Database connection failed</li>
                <?php endif; ?>
                <?php if (!$health_checks['uploads_writable']): ?>
                    <li>Uploads directory is not writable (<?php echo UPLOAD_PATH; ?>)</li>
                <?php endif; ?>
                <?php if (!$health_checks['logs_writable']): ?>
                    <li>Logs directory is not writable (<?php echo LOGS_PATH; ?>)</li>
                <?php endif; ?>
            </ul>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <!-- Info boxes -->
        <div class="row">
            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-info elevation-1"><i class="fas fa-users"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Total Users</span>
                        <span class="info-box-number"><?php echo $stats['total_users']; ?></span>
                        <span class="info-box-text text-muted"><?php echo $stats['active_users']; ?> Active</span>
                    </div>
                </div>
            </div>

            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-success elevation-1"><i class="fas fa-user-tag"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Roles</span>
                        <span class="info-box-number"><?php echo $stats['total_roles']; ?></span>
                        <span class="info-box-text text-muted"><?php echo $stats['total_permissions']; ?> Permissions</span>
                    </div>
                </div>
            </div>

            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-sign-in-alt"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Today's Logins</span>
                        <span class="info-box-number"><?php echo $stats['today_logins']; ?></span>
                        <span class="info-box-text text-muted"><?php echo $stats['failed_logins']; ?> Failed</span>
                    </div>
                </div>
            </div>

            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-database"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Database Size</span>
                        <span class="info-box-number"><?php echo $stats['database_size']['size_mb'] ?? 'N/A'; ?> MB</span>
                        <span class="info-box-text text-muted"><?php echo $stats['system_logs']; ?> Logs Today</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Activity Chart -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            User Activity (Last 7 Days)
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="activityChart" style="min-height: 300px; height: 300px; max-height: 300px; max-width: 100%;"></canvas>
                    </div>
                </div>
            </div>

            <!-- Top Users -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-trophy mr-1"></i>
                            Most Active Users (7 Days)
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <ul class="products-list product-list-in-card pl-2 pr-2">
                            <?php foreach ($top_users as $index => $user): ?>
                            <li class="item">
                                <div class="product-img">
                                    <span class="badge badge-<?php 
                                        echo $index == 0 ? 'warning' : ($index == 1 ? 'secondary' : ($index == 2 ? 'bronze' : 'light'));
                                    ?> p-3">
                                        #<?php echo $index + 1; ?>
                                    </span>
                                </div>
                                <div class="product-info">
                                    <a href="<?php echo base_url('admin/users/view.php?id=' . $user['user_id']); ?>" class="product-title">
                                        <?php echo escape_html($user['first_name'] . ' ' . $user['last_name']); ?>
                                        <span class="badge badge-info float-right"><?php echo $user['action_count']; ?> actions</span>
                                    </a>
                                    <span class="product-description">
                                        <?php echo escape_html($user['username']); ?>
                                    </span>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Recent Users -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas                             <i class="fas fa-user-plus mr-1"></i>
                            Recent User Registrations
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('admin/users/create.php'); ?>" class="btn btn-sm btn-primary">
                                <i class="fas fa-plus"></i> Add User
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>User</th>
                                        <th>Username</th>
                                        <th>Role</th>
                                        <th>Status</th>
                                        <th>Joined</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_users as $user): ?>
                                    <tr>
                                        <td>
                                            <?php echo escape_html($user['first_name'] . ' ' . $user['last_name']); ?>
                                        </td>
                                        <td><?php echo escape_html($user['username']); ?></td>
                                        <td>
                                            <?php 
                                            $role_name = db_fetch_value("SELECT role_name FROM roles WHERE role_id = ?", [$user['role_id']]);
                                            echo escape_html($role_name);
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($user['is_active']): ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge badge-danger">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo time_ago($user['created_at']); ?></td>
                                        <td>
                                            <a href="<?php echo base_url('admin/users/view.php?id=' . $user['user_id']); ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="<?php echo base_url('admin/users/edit.php?id=' . $user['user_id']); ?>" 
                                               class="btn btn-sm btn-primary" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer text-center">
                        <a href="<?php echo base_url('admin/users/index.php'); ?>">View All Users</a>
                    </div>
                </div>
            </div>

            <!-- Recent Audit Logs -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history mr-1"></i>
                            Recent Activity Log
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('admin/users/audit-logs.php'); ?>" class="btn btn-sm btn-primary">
                                View All Logs
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Time</th>
                                        <th>User</th>
                                        <th>Action</th>
                                        <th>Details</th>
                                        <th>IP</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_audit as $log): ?>
                                    <tr>
                                        <td><?php echo time_ago($log['created_at']); ?></td>
                                        <td>
                                            <?php if ($log['user_id']): ?>
                                                <a href="<?php echo base_url('admin/users/view.php?id=' . $log['user_id']); ?>">
                                                    <?php echo escape_html($log['first_name'] . ' ' . $log['last_name']); ?>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">System</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge badge-<?php 
                                                echo $log['action'] == 'login' ? 'success' : 
                                                    ($log['action'] == 'logout' ? 'warning' : 
                                                    ($log['action'] == 'create' ? 'info' : 
                                                    ($log['action'] == 'update' ? 'primary' : 
                                                    ($log['action'] == 'delete' ? 'danger' : 'secondary'))));
                                            ?>">
                                                <?php echo ucfirst($log['action']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php 
                                            $details = [];
                                            if ($log['table_name']) {
                                                $details[] = str_replace('_', ' ', $log['table_name']);
                                            }
                                            if ($log['record_id']) {
                                                $details[] = '#' . $log['record_id'];
                                            }
                                            echo escape_html(implode(' ', $details));
                                            ?>
                                        </td>
                                        <td>
                                            <small class="text-muted"><?php echo $log['ip_address'] ?? 'N/A'; ?></small>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- System Information -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle mr-1"></i>
                            System Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3 col-sm-6">
                                <strong>PHP Version:</strong>
                                <p><?php echo phpversion(); ?></p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>MySQL Version:</strong>
                                <p><?php 
                                    $version = db_fetch_value("SELECT VERSION()");
                                    echo $version;
                                ?></p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>Server Software:</strong>
                                <p><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'; ?></p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>Max Upload Size:</strong>
                                <p><?php echo ini_get('upload_max_filesize'); ?></p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>Memory Limit:</strong>
                                <p><?php echo ini_get('memory_limit'); ?></p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>Max Execution Time:</strong>
                                <p><?php echo ini_get('max_execution_time'); ?>s</p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>Session Save Path:</strong>
                                <p><?php echo session_save_path() ?: 'Default'; ?></p>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <strong>Timezone:</strong>
                                <p><?php echo date_default_timezone_get(); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

<script>
$(document).ready(function() {
    // Activity Chart
    const ctx = document.getElementById('activityChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($activity_data['labels']); ?>,
            datasets: [{
                label: 'Logins',
                data: <?php echo json_encode($activity_data['logins']); ?>,
                borderColor: 'rgb(40, 167, 69)',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                tension: 0.1,
                fill: true
            }, {
                label: 'Actions',
                data: <?php echo json_encode($activity_data['actions']); ?>,
                borderColor: 'rgb(23, 162, 184)',
                backgroundColor: 'rgba(23, 162, 184, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
});
</script>

<style>
/* Custom bronze color for 3rd place */
.badge.bronze {
    background-color: #cd7f32;
    color: white;
}
.products-list .item {
    padding: 10px 0;
    border-bottom: 1px solid #f4f4f4;
}
.products-list .item:last-child {
    border-bottom: none;
}
</style>

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