<?php
session_start();
include_once('includes/config.php');

if (strlen($_SESSION["aid"]) == 0) {
    header('location:logout.php');
    exit;
}

// Test database connectivity and verify all features
$tests = [];

// 1. Test database connection
$tests[] = [
    'name' => 'Database Connection',
    'status' => mysqli_ping($con) ? 'success' : 'failed',
    'message' => mysqli_ping($con) ? 'Connected to MySQL successfully' : 'Failed to connect to database'
];

// 2. Check required tables exist
$requiredTables = ['admin', 'users', 'orders', 'products', 'category', 'subcategory', 'user_details'];
$missingTables = [];

foreach ($requiredTables as $table) {
    $result = mysqli_query($con, "SHOW TABLES LIKE '$table'");
    if (mysqli_num_rows($result) == 0) {
        $missingTables[] = $table;
    }
}

$tests[] = [
    'name' => 'Database Tables',
    'status' => empty($missingTables) ? 'success' : 'warning',
    'message' => empty($missingTables) ? 'All required tables exist' : 'Missing tables: ' . implode(', ', $missingTables)
];

// 3. Test Admin table
$adminCheck = mysqli_query($con, "SELECT COUNT(*) as count FROM admin");
$adminCount = mysqli_fetch_assoc($adminCheck);
$tests[] = [
    'name' => 'Admin Accounts',
    'status' => $adminCount['count'] > 0 ? 'success' : 'warning',
    'message' => $adminCount['count'] . ' admin account(s) found'
];

// 4. Test Orders table
$ordersCheck = mysqli_query($con, "SELECT COUNT(*) as count FROM orders");
$ordersCount = mysqli_fetch_assoc($ordersCheck);
$tests[] = [
    'name' => 'Orders Data',
    'status' => 'success',
    'message' => $ordersCount['count'] . ' order(s) in database'
];

// 5. Test Products table
$productsCheck = mysqli_query($con, "SELECT COUNT(*) as count FROM products");
$productsCount = mysqli_fetch_assoc($productsCheck);
$tests[] = [
    'name' => 'Products Data',
    'status' => 'success',
    'message' => $productsCount['count'] . ' product(s) in database'
];

// 6. Test Users table
$usersCheck = mysqli_query($con, "SELECT COUNT(*) as count FROM users");
$usersCount = mysqli_fetch_assoc($usersCheck);
$tests[] = [
    'name' => 'Users Data',
    'status' => 'success',
    'message' => $usersCount['count'] . ' user(s) registered'
];

// 7. Test Export functionality
$tests[] = [
    'name' => 'Export Functionality',
    'status' => file_exists('export-orders.php') ? 'success' : 'failed',
    'message' => file_exists('export-orders.php') ? 'Export file exists and ready' : 'Export file missing'
];

// 8. Test Notifications API
$tests[] = [
    'name' => 'Notifications API',
    'status' => file_exists('api/notifications.php') ? 'success' : 'failed',
    'message' => file_exists('api/notifications.php') ? 'Notifications API ready' : 'Notifications API missing'
];

// 9. Test Settings page
$tests[] = [
    'name' => 'Settings Page',
    'status' => file_exists('settings.php') ? 'success' : 'failed',
    'message' => file_exists('settings.php') ? 'Settings page ready' : 'Settings page missing'
];

// 10. Test Dashboard
$tests[] = [
    'name' => 'Dashboard',
    'status' => file_exists('dashboard.php') ? 'success' : 'failed',
    'message' => file_exists('dashboard.php') ? 'Dashboard ready' : 'Dashboard missing'
];

$totalTests = count($tests);
$passedTests = count(array_filter($tests, function ($test) {
    return $test['status'] == 'success'; }));
$failedTests = count(array_filter($tests, function ($test) {
    return $test['status'] == 'failed'; }));
$warningTests = count(array_filter($tests, function ($test) {
    return $test['status'] == 'warning'; }));

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>System Test - Awesome Mall Admin</title>
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="js/all.min.js" crossorigin="anonymous"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-check-circle me-2"></i> System Test</h1>
                            <p>Verify database connectivity and feature availability</p>
                        </div>
                    </div>

                    <!-- Test Summary -->
                    <div class="row mb-4">
                        <div class="col-md-4 mb-3">
                            <div class="stat-card">
                                <div class="stat-icon success">
                                    <i class="fas fa-check"></i>
                                </div>
                                <div class="stat-value">
                                    <?php echo $passedTests; ?>/
                                    <?php echo $totalTests; ?>
                                </div>
                                <div class="stat-label">Tests Passed</div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="stat-card">
                                <div class="stat-icon warning">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </div>
                                <div class="stat-value">
                                    <?php echo $warningTests; ?>
                                </div>
                                <div class="stat-label">Warnings</div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="stat-card">
                                <div class="stat-icon danger">
                                    <i class="fas fa-times"></i>
                                </div>
                                <div class="stat-value">
                                    <?php echo $failedTests; ?>
                                </div>
                                <div class="stat-label">Failed</div>
                            </div>
                        </div>
                    </div>

                    <!-- Test Results -->
                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list-check me-2"></i>System Test Results</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="30%">Test Name</th>
                                        <th>Result</th>
                                        <th width="10%">Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($tests as $index => $test) {
                                        $statusClass = $test['status'];
                                        $statusIcon = '';
                                        switch ($test['status']) {
                                            case 'success':
                                                $statusIcon = 'fa-check-circle text-success';
                                                break;
                                            case 'warning':
                                                $statusIcon = 'fa-exclamation-triangle text-warning';
                                                break;
                                            case 'failed':
                                                $statusIcon = 'fa-times-circle text-danger';
                                                break;
                                        }
                                        ?>
                                        <tr>
                                            <td>
                                                <?php echo $index + 1; ?>
                                            </td>
                                            <td><strong>
                                                    <?php echo $test['name']; ?>
                                                </strong></td>
                                            <td>
                                                <?php echo $test['message']; ?>
                                            </td>
                                            <td>
                                                <i class="fas <?php echo $statusIcon; ?> fa-lg"></i>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>

                            <?php if ($failedTests == 0 && $warningTests == 0) { ?>
                                <div class="alert alert-success mt-3">
                                    <i class="fas fa-check-circle me-2"></i>
                                    <strong>All systems operational!</strong> Your admin portal is ready to use.
                                </div>
                            <?php } elseif ($failedTests > 0) { ?>
                                <div class="alert alert-danger mt-3">
                                    <i class="fas fa-exclamation-circle me-2"></i>
                                    <strong>Action required!</strong> Some critical tests failed. Please check the results
                                    above.
                                </div>
                            <?php } else { ?>
                                <div class="alert alert-warning mt-3">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    <strong>Minor issues detected.</strong> Your system is functional but some warnings need
                                    attention.
                                </div>
                            <?php } ?>

                            <!-- Database Info -->
                            <div class="mt-4 p-3 bg-light rounded">
                                <h6><i class="fas fa-database me-2"></i>Database Information</h6>
                                <div class="row mt-3">
                                    <div class="col-md-3">
                                        <small class="text-muted">Server</small>
                                        <p class="mb-0"><strong>
                                                <?php echo DB_SERVER; ?>
                                            </strong></p>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Database</small>
                                        <p class="mb-0"><strong>
                                                <?php echo DB_NAME; ?>
                                            </strong></p>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">MySQL Version</small>
                                        <p class="mb-0"><strong>
                                                <?php echo mysqli_get_server_info($con); ?>
                                            </strong></p>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">PHP Version</small>
                                        <p class="mb-0"><strong>
                                                <?php echo phpversion(); ?>
                                            </strong></p>
                                    </div>
                                </div>
                            </div>

                            <div class="text-center mt-4">
                                <a href="dashboard.php" class="btn btn-primary">
                                    <i class="fas fa-home me-2"></i>Back to Dashboard
                                </a>
                                <button onclick="location.reload()" class="btn btn-outline-primary">
                                    <i class="fas fa-sync me-2"></i>Rerun Tests
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>
    <script src="js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
</body>

</html>
