<?php
require_once 'main/initial.php';
if (!isset($_SESSION['admin_id'])) {
    header('Location: admin_login.php');
    exit;
}
// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin_login.php');
    exit;
}
// Fetch users
$stmt = $con->query('SELECT * FROM users ');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
$page_title = 'لوحة التحكم';
include 'includes/header.php';
// Handle user deletion
if (isset($_POST['delete_user_id'])) {
    $delete_id = (int)$_POST['delete_user_id'];
    // Delete QR image file(s) for this user (unified directory)
    $stmt_qr = $con->prepare('SELECT path FROM qrcodes WHERE user_id = ?');
    $stmt_qr->execute([$delete_id]);
    $allFiles = $stmt_qr->fetchAll(PDO::FETCH_ASSOC);
    foreach ($allFiles as $qr) {
        $f1 = 'uploads/qrcodes/' . $qr['path'];
        if (!empty($qr['path']) && file_exists($f1)) { @unlink($f1); }
        // Clean up any leftover old-data folder files just in case
        $f2 = 'uploads/qrcodes_data/' . $qr['path'];
        if (!empty($qr['path']) && file_exists($f2)) { @unlink($f2); }
    }
    // Delete user (will also delete QR code record due to FK)
    $stmt = $con->prepare('DELETE FROM users WHERE id = ?');
    $stmt->execute([$delete_id]);
    header('Location: admin_dashboard.php');
    exit;
}
?>

<div class="container mt-4" dir="rtl">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-row-reverse">
        <h2 class="fw-bold">لوحة التحكم</h2>
        <div class="d-flex gap-2">
            <a href="export_users.php" class="btn btn-success">تصدير إلى Excel</a>
            <a href="?logout=1" class="btn btn-danger">تسجيل الخروج</a>
        </div>
    </div>
    <div class="card p-3 shadow-sm">
        <h4 class="mb-3">المستخدمون المسجلون</h4>
        <div class="table-responsive">
            <table id="usersTable" dir="rtl" class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th class="text-center">#</th>
                        <th class="text-end">رقم الشخص</th>
                        <th class="text-end">اسم الشخص</th>
                        <th class="text-end">اسم الشركة</th>
                        <th class="text-end">الهاتف</th>
                        <th class="text-end">تاريخ التسجيل</th>
                        <th class="text-center">مسح الرمز</th>
                        <th class="text-center">التحكم</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $i = 1;
                    foreach ($users as $user): 
                        // Get QR info for this user (renamed table)
                        $stmt_qr = $con->prepare('SELECT * FROM qrcodes WHERE user_id = ? ORDER BY created_at DESC LIMIT 1');
                        $stmt_qr->execute([$user['id']]);
                        $qr = $stmt_qr->fetch(PDO::FETCH_ASSOC);
                        $qr_img = ($qr && !empty($qr['path'])) ? htmlspecialchars('uploads/qrcodes/' . $qr['path']) : '#';
                        $profile_link = 'user.php?id=' . $user['id'];
                        $api_link = 'api/scanqrcode.php?id=' . $user['id'];
                    ?>
                        <tr>
                            <td><?php echo $i++; ?></td>
                            <!-- الرقم المميز تمت إزالته -->
                            <td><?php echo htmlspecialchars($user['id']); ?></td>
                            <td><?php echo htmlspecialchars($user['name']); ?></td>
                            <td><?php echo htmlspecialchars($user['company_name']); ?></td>
                            <td><?php echo htmlspecialchars($user['phone']); ?></td>
                            <td><?php echo htmlspecialchars($user['created_at']); ?></td>
                            <td>                                
                                <?php if ($qr): ?>
                                    <span class="badge <?php echo ((int)$qr['scanned']===1)?'bg-success':'bg-secondary'; ?> me-1">
                                        <?php echo ((int)$qr['scanned']===1)?'تم المسح':'لم يُمسح'; ?>
                                    </span>
                                <?php endif; ?></td>
                            <td>
                                <a href="<?php echo $qr_img; ?>" target="_blank" class="btn btn-sm btn-outline-primary mb-1">رمز البيانات</a>
                                <a href="<?php echo $profile_link; ?>" target="_blank" class="btn btn-sm btn-outline-secondary mb-1">الملف</a>
                                <form method="POST" action="" style="display:inline;" onsubmit="return confirm('هل أنت متأكد أنك تريد حذف هذا المستخدم؟');">
                                    <input type="hidden" name="delete_user_id" value="<?php echo $user['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger mb-1">حذف</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<!-- DataTables JS & CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    $('#usersTable').DataTable({
        language: {
            url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json'
        }
    });
});
</script>
<?php include 'includes/footer.php'; ?>