<?php
require_once __DIR__ . '/connect.php';
if (!is_logged_in()) {
    header('Location: login.php');
    exit;
}

$hasEmailCol = false;
if ($res = $conn->query("SHOW COLUMNS FROM users LIKE 'email'")) {
    $hasEmailCol = $res->num_rows > 0;
    $res->free();
}

if (isset($_GET['export']) && $_GET['export'] === '1') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=users_export_' . date('Ymd_His') . '.csv');
    $out = fopen('php://output', 'w');
    // Write UTF-8 BOM so Excel detects UTF-8 and displays Arabic correctly
    fprintf($out, "\xEF\xBB\xBF");
    if ($hasEmailCol) {
        fputcsv($out, ['id', 'name', 'email', 'created_at']);
        $res = $conn->query('SELECT id,name,email,created_at FROM users ORDER BY id');
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                fputcsv($out, [$row['id'], $row['name'], $row['email'], $row['created_at']]);
            }
            $res->free();
        }
    } else {
        fputcsv($out, ['id', 'name', 'created_at']);
        $res = $conn->query('SELECT id,name,created_at FROM users ORDER BY id');
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                fputcsv($out, [$row['id'], $row['name'], $row['created_at']]);
            }
            $res->free();
        }
    }
    fclose($out);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_all'])) {
    $conn->query('TRUNCATE TABLE users');
    header('Location: users.php?deleted=1');
    exit;
}

$users = [];
$res = $conn->query($hasEmailCol ? 'SELECT id,name,email,created_at FROM users ORDER BY id DESC' : 'SELECT id,name,created_at FROM users ORDER BY id DESC');
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $users[] = $row;
    }
    $res->free();
}
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Users</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="logo.png">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background: #f7f7f9;
        }

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        button,
        .btn {
            padding: 8px 12px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-export {
            background: #198754;
            color: #fff;
            text-decoration: none;
        }

        .btn-delete {
            background: #dc3545;
            color: #fff;
        }

        .btn-logout {
            background: #6c757d;
            color: #fff;
            text-decoration: none;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 8px 20px rgba(0, 0, 0, .05);
        }

        .table th,
        .table td {
            padding: 10px 12px;
            border-bottom: 1px solid #eee;
            text-align: left;
        }

        .table th {
            background: #f2f4f8;
            font-weight: 600;
        }

        .empty {
            text-align: center;
            padding: 40px;
            color: #777;
        }
    </style>
</head>

<body>
    <div class="header">
        <h2>Users</h2>
        <div class="actions">
            <a class="btn btn-export" href="users.php?export=1">Export to Excel</a>
            <form method="post" id="deleteAllForm" style="display:inline">
                <input type="hidden" name="delete_all" value="1">
                <button type="submit" class="btn btn-delete">Delete All</button>
            </form>
            <a class="btn btn-logout" href="logout.php">Logout</a>
        </div>
    </div>

    <table class="table">
        <tr>
            <th>ID</th>
            <th>Name</th><?php if ($hasEmailCol): ?><th>Email</th><?php endif; ?><th>Created</th>
        </tr>
        <?php if (count($users) === 0): ?>
            <tr>
                <td colspan="<?php echo $hasEmailCol ? '4' : '3'; ?>" class="empty">No users</td>
            </tr>
        <?php else: ?>
            <?php foreach ($users as $u): ?>
                <tr>
                    <td><?php echo htmlspecialchars($u['id']); ?></td>
                    <td><?php echo htmlspecialchars($u['name']); ?></td>
                    <?php if ($hasEmailCol): ?>
                        <td><?php echo htmlspecialchars($u['email']); ?></td>
                    <?php endif; ?>
                    <td><?php echo htmlspecialchars($u['created_at']); ?></td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </table>

    <script>
        const form = document.getElementById('deleteAllForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                Swal.fire({
                    title: 'Delete all users?',
                    text: 'This will remove all records and reset IDs.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete all',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                });
            });
        }
        <?php if (isset($_GET['deleted']) && $_GET['deleted'] === '1'): ?>
            Swal.fire({
                title: 'All users deleted',
                icon: 'success'
            });
        <?php endif; ?>
    </script>
</body>

</html>