<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('user_management');

$pdo = getDB();

// Handle Add/Edit User
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
        $id = (int)$_POST['id'];
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $role_id = (int)$_POST['role_id'];
        $status = isset($_POST['status']) ? 1 : 0;

        if (empty($name) || empty($email)) {
            $_SESSION['error'] = 'Please fill required fields.';
        } else {
            try {
                if ($_POST['action'] === 'add') {
                    $password = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO users (role_id, name, email, phone, password, status) VALUES (?,?,?,?,?,?)");
                    $stmt->execute([$role_id, $name, $email, $phone, $password, $status]);
                    logActivity('Created User', 'Users', $pdo->lastInsertId(), "Created user: $name");
                    $_SESSION['success'] = 'User created successfully.';
                } else {
                    $sql = "UPDATE users SET role_id=?, name=?, email=?, phone=?, status=? WHERE id=?";
                    $params = [$role_id, $name, $email, $phone, $status, $id];
                    if (!empty($_POST['password'])) {
                        $sql = "UPDATE users SET role_id=?, name=?, email=?, phone=?, password=?, status=? WHERE id=?";
                        $password = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
                        $params = [$role_id, $name, $email, $phone, $password, $status, $id];
                    }
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    logActivity('Updated User', 'Users', $id, "Updated user: $name");
                    $_SESSION['success'] = 'User updated successfully.';
                }
            } catch (PDOException $e) {
                $_SESSION['error'] = 'Error: ' . $e->getMessage();
            }
        }
        header('Location: users.php');
        exit;
    }

    // Handle Delete
    if ($_POST['action'] === 'delete' && isset($_POST['id'])) {
        $id = (int)$_POST['id'];
        if ($id == $_SESSION['user_id']) {
            $_SESSION['error'] = 'You cannot delete your own account.';
        } elseif ($id == 1) {
            $_SESSION['error'] = 'Cannot delete Super Admin.';
        } else {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
            $stmt->execute([$id]);
            logActivity('Deleted User', 'Users', $id);
            $_SESSION['success'] = 'User deleted successfully.';
        }
        header('Location: users.php');
        exit;
    }
}

$users = $pdo->query("SELECT u.*, r.role_name FROM users u JOIN roles r ON u.role_id = r.id ORDER BY u.id")->fetchAll();
$roles = $pdo->query("SELECT * FROM roles WHERE status=1")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-users me-2"></i>Users</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal" onclick="resetUserForm()"><i class="fas fa-plus me-1"></i>Add User</button>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="usersTable" class="table table-hover datatable">
                        <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Role</th><th>Status</th><th>Last Login</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($users as $u): ?>
                            <tr>
                                <td><?= $u['id'] ?></td>
                                <td><strong><?= htmlspecialchars($u['name']) ?></strong></td>
                                <td><?= htmlspecialchars($u['email']) ?></td>
                                <td><?= htmlspecialchars($u['phone']) ?></td>
                                <td><span class="badge bg-primary"><?= htmlspecialchars($u['role_name']) ?></span></td>
                                <td><?= $u['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td><?= $u['last_login_at'] ? date('Y-m-d h:i A', strtotime($u['last_login_at'])) : 'Never' ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="editUser(<?= htmlspecialchars(json_encode($u)) ?>)"><i class="fas fa-edit"></i></button>
                                    <?php if ($u['id'] != 1 && $u['id'] != $_SESSION['user_id']): ?>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this user?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $u['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- User Modal -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header"><h5 class="modal-title" id="userModalTitle">Add User</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" name="action" id="userAction" value="add">
                    <input type="hidden" name="id" id="userId" value="0">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Full Name *</label>
                            <input type="text" name="name" id="uName" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email *</label>
                            <input type="email" name="email" id="uEmail" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Phone</label>
                            <input type="text" name="phone" id="uPhone" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Role *</label>
                            <select name="role_id" id="uRole" class="form-select" required>
                                <?php foreach ($roles as $r): ?>
                                <option value="<?= $r['id'] ?>"><?= htmlspecialchars($r['role_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password <?= isset($edit) ? '(leave blank to keep)' : '*' ?></label>
                        <input type="password" name="password" id="uPassword" class="form-control" <?= !isset($edit) ? 'required' : '' ?>>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" name="status" id="uStatus" class="form-check-input" checked>
                        <label class="form-check-label">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetUserForm() {
    $('#userAction').val('add');
    $('#userId').val(0);
    $('#userModalTitle').text('Add User');
    $('#uName').val('');
    $('#uEmail').val('');
    $('#uPhone').val('');
    $('#uPassword').val('');
    $('#uRole').val(1);
    $('#uStatus').prop('checked', true);
    $('#uPassword').prop('required', true);
}

function editUser(user) {
    $('#userAction').val('edit');
    $('#userId').val(user.id);
    $('#userModalTitle').text('Edit User: ' + user.name);
    $('#uName').val(user.name);
    $('#uEmail').val(user.email);
    $('#uPhone').val(user.phone);
    $('#uPassword').val('');
    $('#uRole').val(user.role_id);
    $('#uStatus').prop('checked', user.status == 1);
    $('#uPassword').prop('required', false);
    $('#userModal').modal('show');
}
</script>

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