<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Add / Edit / Delete) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // 1. DELETE ADMIN
    if ($action === 'delete' && isset($_POST['admin_id'])) {
        $target_id = (int)$_POST['admin_id'];
        
        // Prevent admin from deleting themselves
        if ($target_id === (int)$_SESSION['admin_id']) {
            $_SESSION['swal_error'] = "You cannot delete your own account while logged in.";
        } else {
            $del_q = "DELETE FROM `admins` WHERE `id` = ?";
            if ($stmt = mysqli_prepare($conn, $del_q)) {
                mysqli_stmt_bind_param($stmt, "i", $target_id);
                if (mysqli_stmt_execute($stmt)) {
                    $_SESSION['swal_success'] = "Administrator removed successfully.";
                    $_SESSION['swal_title'] = "Deleted";
                }
                mysqli_stmt_close($stmt);
            }
        }
    }

    // 2. ADD NEW ADMIN
    elseif ($action === 'add') {
        $user = mysqli_real_escape_string($conn, $_POST['username']);
        $pass = mysqli_real_escape_string($conn, $_POST['password']);

        $add_q = "INSERT INTO `admins` (`username`, `password`, `created_at`) VALUES (?, ?, NOW())";
        if ($stmt = mysqli_prepare($conn, $add_q)) {
            mysqli_stmt_bind_param($stmt, "ss", $user, $pass);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "New administrator '$user' added.";
                $_SESSION['swal_title'] = "Created";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. EDIT ADMIN
    elseif ($action === 'edit' && isset($_POST['admin_id'])) {
        $target_id = (int)$_POST['admin_id'];
        $user = mysqli_real_escape_string($conn, $_POST['username']);
        $pass = mysqli_real_escape_string($conn, $_POST['password']);

        $upd_q = "UPDATE `admins` SET `username` = ?, `password` = ? WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "ssi", $user, $pass, $target_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Administrator credentials updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: system_settings.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION & FETCH ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `admins` ");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

$query = "SELECT `id`, `username`, `password`, `created_at` FROM `admins` ORDER BY `created_at` DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Access Control</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">System Administrators</h1>
            <p class="text-slate-400 mt-1 text-sm">Manage administrative credentials and security access</p>
        </div>
        <!--
        <button onclick="adminModal('add')" class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2.5 rounded-lg text-sm font-bold shadow-lg shadow-blue-900/20 flex items-center gap-2 transition-all">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path></svg>
            Add New Admin
        </button>
        -->
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[800px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">Admin Username</th>
                        <th class="p-4">Encrypted Password (Raw)</th>
                        <th class="p-4">Date Created</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): 
                            $is_current = ((int)$row['id'] === (int)$_SESSION['admin_id']);
                        ?>
                        <tr class="hover:bg-slate-800/30 transition-colors <?php echo $is_current ? 'bg-blue-500/5' : ''; ?>">
                            <td class="p-4 font-bold text-slate-100 flex items-center gap-2">
                                <?php echo htmlspecialchars($row['username'] ?? ''); ?>
                                <?php if($is_current): ?>
                                    <span class="text-[9px] bg-blue-500/20 text-blue-400 px-1.5 py-0.5 rounded border border-blue-500/20">YOU</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 font-mono text-xs text-slate-500">
                                <?php echo str_repeat('•', 8); ?> </td>
                            <td class="p-4 text-slate-400">
                                <?php echo date('M d, Y', strtotime($row['created_at'])); ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <button onclick='adminModal("edit", <?php echo json_encode($row); ?>)' class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Edit</button>
                                    
                                    <?php if(!$is_current): ?>
                                    <form method="POST" class="inline" onsubmit="return confirm('Revoke admin access?');">
                                        <input type="hidden" name="admin_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Remove</button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="p-12 text-center text-slate-500 italic">No administrative accounts found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function adminModal(mode, data = null) {
    let title = mode === 'add' ? 'Create Administrator' : 'Update Credentials';
    let btnText = mode === 'add' ? 'Create Account' : 'Save Changes';
    let html = `
        <form id="adminForm" method="POST" class="text-left mt-4">
            <input type="hidden" name="action" value="${mode}">
            ${mode === 'edit' ? `<input type="hidden" name="admin_id" value="${data.id}">` : ''}
            
            <div class="mb-4">
                <label class="text-[10px] uppercase font-bold text-slate-500">Username</label>
                <input type="text" name="username" value="${data ? data.username : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
            </div>

            <div class="mb-2">
                <label class="text-[10px] uppercase font-bold text-slate-500">${mode === 'edit' ? 'Change Password' : 'Password'}</label>
                <input type="text" name="password" value="${data ? data.password : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                <p class="text-[10px] text-slate-500 mt-2 italic">Note: Use a strong, unique password to ensure system security.</p>
            </div>
        </form>
    `;

    Swal.fire({
        title: title,
        background: '#0f172a',
        color: '#f1f5f9',
        html: html,
        showCancelButton: true,
        confirmButtonText: btnText,
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('adminForm').submit(); }
    });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['swal_error'])): ?>
    Swal.fire({ title: 'System Warning', text: '<?php echo $_SESSION['swal_error']; ?>', icon: 'error', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#ef4444' });
    <?php unset($_SESSION['swal_error']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>